john
john

Reputation: 2861

jquery traversal question

Given:

<div>
   <div id="div1">
     <input type="radio" .. />
   </div>

   <div id="div2">

   </div>

   <div id="div3">
     <button type="button">a button</button>
   </div>
</div>

So, I am currently in the context of the <input> via its click event. I need to traverse this (using parent / children somehow) to select the button in div3 (without using a class, id etc) and enable/disable it. Any ideas?

Upvotes: 1

Views: 59

Answers (4)

Chad Moran
Chad Moran

Reputation: 12854

$('input').click(function() {
    $(this).parent().parent().find('button').attr('disabled', 'disabled');
});

Though I highly recommend using some sort of class/ID to help out because DOM traversal can be brittle.

Upvotes: 2

Tim B James
Tim B James

Reputation: 20374

If the Html hierarchy never changes, then this will work.

$().ready(function(){
    $('input').click(function(){
        var elm = $(this).parent().parent().find('div').eq(2).find('button');
    });
 });

Upvotes: 0

Dharmesh
Dharmesh

Reputation: 1059

you can try this :

$('#div1 > input').click(function(){
    $('#div3 > button').attr('disabled','disabled')
})

Upvotes: 0

David Tang
David Tang

Reputation: 93694

Without any information about the logical relation between the elements, I can only make assumptions.

If the structure will remain exactly the same, then:

$(this).parent().next().next().find('button').attr('disabled', true);

If the target div is always the last element in the container, then:

$(this).parent().siblings(':last').find('button').attr('disabled', true);

If there is only ever one <button> in the container, then:

$(this).parents().eq(1).find('button').attr('disabled', true);

Upvotes: 3

Related Questions