I need to change a "for" label from an extension using javascript. I am unsure how to do this. Thank in advance for the help!
<input id="theCheckboxId" type="checkbox" name="theCheckBoxName" />
<label for="theCheckBox">The text I want to change</label>
DEMO
First give the label an id
<label id="lbl1" for="theCheckBox">The text I want to change</label>
then do
document.getElementById("lbl1").setAttribute("for", "theCheckboxId");
EDIT
Wait, did you want to change the for
value, or change the actual text of the label? In any event, here's how you would change the text:
if (label.textContent)
label.textContent = "New Text";
else if (label.innerText)
label.innerText = "New Text"
else
label.innerHTML = "New Text";
You didn't ask, but if you are using jQuery, you can do it a bit simpler via:
$('label[for="theCheckBox"]').text('your new text')
That said, the advice of giving it an ID instead is definitely the most performant option, though we don't know if you have access to the HTML or not (as if you did, you could probably just change the text right there)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With