Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing an html "for" label with java script

Tags:

javascript

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>
like image 742
Alex Mousavi Avatar asked Jan 11 '12 04:01

Alex Mousavi


2 Answers

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";
like image 182
Adam Rackis Avatar answered Sep 17 '22 19:09

Adam Rackis


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)

like image 38
DA. Avatar answered Sep 19 '22 19:09

DA.