Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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,736 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".