9

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>

3 Answers 3

11

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";
Sign up to request clarification or add additional context in comments.

1 Comment

Another way to change the 'for' value: document.getElementById("lbl1").htmlFor = "theCheckboxId";
3

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)

Comments

2

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/

7 Comments

Yeah, I'm not sure if he wants to change the text, or the for attribute. +1 though
@AdamRackis: Take a quick look at the current text in the example. ;) The title is deceiving I must admit.
Yes, that was the text that led me to believe he might want to change the text......
@AdamRackis: Ah, yeah I see now that you had already updated.
@AdamRackis: No, I know you didn't. :) Yeah, I've never heard anyone call it a "for" label.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.