Alex Mousavi
Alex Mousavi

Reputation: 393

Changing an html "for" label with java script

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>

Upvotes: 9

Views: 11924

Answers (3)

user1106925
user1106925

Reputation:

To change the text, do this:

document.getElementById('theCheckboxId').nextElementSibling.textContent = 'newValue';

or this:

document.querySelector('#theCheckboxId + label').textContent = 'newValue';

Or if you need to support older browsers, do this:

function nextElement( el ) {
    while( (el = el.nextSibling) && el.nodeType !== 1 );
    return el;
}

nextElement( document.getElementById('theCheckboxId') ).innerHTML = 'newValue';

http://jsfiddle.net/3kEYw/

Upvotes: 2

DA.
DA.

Reputation: 40671

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)

Upvotes: 3

Adam Rackis
Adam Rackis

Reputation: 83356

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";

Upvotes: 11

Related Questions