Roy
Roy

Reputation: 751

How to select parent's sibling's children

HTML:

<div class="parent"> 
  <input></input> 
  <button></button> 
</div> 
<div class="siblings"> 
  <p class="children"></p> 
</div> 

jQuery:

$('button').click(function(){ 
  if($(this).siblings('input') != ""){ 
    var addTo = $(this).siblings('input').val(); 
    $(this).parent('parent').siblings('siblings').children('children').html(addTo); 
  } 
}); 

Why doesn't it work? I want to grab the value from the input, and replace the content of p.

Upvotes: 9

Views: 23916

Answers (3)

arnorhs
arnorhs

Reputation: 10429

You are referencing the selectors for the classes as if they are elements, (they are missing the dot: .) -- so you probably want to change it into something like:

$(this).parent('.parent').siblings('.siblings').children('.children').html(addTo); 

but there's a bunch of other weird stuff there, which you'll want to fix eventually as well. Like others have pointed out, your if statement (if($(this).siblings('input') != ""){) will always evaluate to true, I'm guessing you are trying to see if it's value is empty?

Here's a working complete rewrite fwiw:

$('button').click(function(){
  var input = $(this).siblings('input'),
      val = input.val();
  if(val != ""){ 
    $(this).parent('.parent').find('.children').html(val); 
  }
}); 

Upvotes: 9

apchester
apchester

Reputation: 1144

You could do this via DOM traversal (parents, children and siblings), but I would recommend giving your elements IDs so that they can be uniquely identified on the page.

Your current method is very fragile and would break if you change the page structure, while an ID based method would not.

Upvotes: -1

Chubby Boy
Chubby Boy

Reputation: 31062

The problem is with the following lines:

Instead of:

$(this).parent('parent').siblings('siblings').children('children').html(addTo);

Try this:

$(this).parent().siblings('.siblings').find('.children').html(addTo);

Instead of

$(this).siblings('input') != ""

Try this:

$(this).siblings('input').val() != ""

Upvotes: 4

Related Questions