I have a form element like this:
<div id="myformelement">
<input type="radio" id="option1">
<label for="option2">Option 1</label>
<input type="radio" id="option2">
<label for="option2">Option 2</label>
<input type="radio" id="option3">
<label for="option3">Option 3</label>
<input type="radio" id="option4">
<label for="option4">Option 4</label>
</div>
I want to hide the input fields "option2" and "option3" and their labels.
I can hide the input bullets by addressing the id. Unfortunately the corresponding labels to the input fields only have a "for" tag with the id in it.
How can I do this with javascript (no jquery).
I found this question (Find html label associated with a given input), but this seems only to work with one label within an ID, I can not use this.
Thanks in advance! Kind regards, Malte
I have a form element like this:
<div id="myformelement">
<input type="radio" id="option1">
<label for="option2">Option 1</label>
<input type="radio" id="option2">
<label for="option2">Option 2</label>
<input type="radio" id="option3">
<label for="option3">Option 3</label>
<input type="radio" id="option4">
<label for="option4">Option 4</label>
</div>
I want to hide the input fields "option2" and "option3" and their labels.
I can hide the input bullets by addressing the id. Unfortunately the corresponding labels to the input fields only have a "for" tag with the id in it.
How can I do this with javascript (no jquery).
I found this question (Find html label associated with a given input), but this seems only to work with one label within an ID, I can not use this.
Thanks in advance! Kind regards, Malte
In pure JavaScript you can use querySelector
:
document.querySelector("label[for='option2']").style.display = "none";
You can do it with nextSibling
:
var rdo = document.getElementById("option2");
var lbl;
rdo.style.display = "none";
for (lbl = rdo.nextSibling; lbl && lbl.nodeName.toUpperCase() !== "LABEL"; lbl = lbl.nextSibling) {
}
if (lbl) {
lbl.style.display = "none";
}
But I have a better option for you: It seems to be a well-kept secret that label
elements can contain the input
they relate to, and when they do no for
is required at all. So if you change your HTML to:
<div id="myformelement">
<label><input type="radio" id="option1"> Option 1</label>
<label><input type="radio" id="option2"> Option 2</label>
<label><input type="radio" id="option3"> Option 3</label>
<label><input type="radio" id="option4"> Option 4</label>
</div>
...it gets a lot easier:
document.getElementById("option2").parentNode.style.display = "none";
You just find the input
, traverse up to its parent which is the label
, and hide that (which will hide the input
as well).