Andy Harvey
Andy Harvey

Reputation: 12663

What javascript method to target descendants?

I'm using a javascript function to set the value of a text field, based on the option chosen from a select field.

The javascript contains a lot of other stuff, but only the following is relevant to this question.

$(function (){
    $('.source').live("change", function(e) { 
        var target = $(this).next('.target')[0];
        ----other stuff----
    });
});

I originally had my form set up as follows, and everything worked fine.

<select class="source"></select>
<input class="target"></input>

I've subsequently added some styling, which has required extra divs.

<select class="source"></select>
<div class="level1">
    <div class="level2">
        <input class="target"></input>
    </div>
</div>

Now the javascript function does not work, because the next method only targets siblings and not descendants.

So my question is, what method should I be using to target a specific descendant?

An important fact: this markup is part of a nested form, and is repeated several times on the same page. It is important that the function targets the correct .target field, i.e. immediately subsequent and descendant.

I've tried obvious candidates – .find(), .children() — but these don't seem to work. Would appreciate any ideas or pointers.

Thanks!

Upvotes: 2

Views: 268

Answers (3)

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76890

In your case this would work:

$(function (){
    $('.source').live("change", function(e) { 
        var target = $(this).next().find('.target')[0];
        ----other stuff----
    });
})

;

Upvotes: 2

Linus Thiel
Linus Thiel

Reputation: 39261

It's a descendant of the sibling, so this should do the trick:

var target = $(this).next('.level1').find('.target')[0];

Upvotes: 2

ShankarSangoli
ShankarSangoli

Reputation: 69915

Now that in the new markup structure .target input is wrapped in a div with class level1 you can find that div first using next() and then use find() method to get to the .target input.

$(function (){
    $('.source').live("change", function(e) { 
        var target = $(this).next('.level1').find('.target')[0];
        ----other stuff----
    });
});

Note: Even if you don't pass any selector to next() also it will work fine because it only selects the immediate next sibling optionally filtered by the selector which we pass.

Upvotes: 3

Related Questions