Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

select a specific "label"

Is there a way to select a label that is connected to $(this)? I want to change its text value.

$("label[for=$(this)].text(value);

2 Answers

geoffrey
geoffrey
28,724 Points

By $(this) what do you mean ? I guess a label linked to an input, a select or something like that ? If so here is what I did.

<label for="name">Name:
    <input type="text" id="name" name="name">
</label>

<label for="nickname">Nickname:
    <input type="text" id="nickname" name="nickname">
</label>
<br/>
$(function(){

    $("input[id='name']").click(function(){

        //this allows you to remove only the text contained inside the label tag and not the input.
        $(this).parent().contents().filter(function(){
            return this.nodeType === 3;
        }).remove();

        $(this).parent().prepend("SuperName:");
    });
});

If you want to test it directly, check this fiddle. Click the Name input and you'll see the label 'll be replaced by another text.

One possible way is trying something like this. You don't necessarily need to have the .on() but for the purpose of my example i have used it.

$("label").on('click', function() {
  $(this).html('Changed');
});

See Example: CSSDeck Click on the label text and it will change it's value to "Changed".