Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select parent's sibling's children

Tags:

jquery

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.

like image 776
Roy Avatar asked Jun 08 '13 07:06

Roy


People also ask

How do I select a parent sibling in CSS?

Adjacent Sibling Selector (+) The adjacent sibling selector is used to select an element that is directly after another specific element. Sibling elements must have the same parent element, and "adjacent" means "immediately following".

How to get parent sibling in jQuery?

jQuery siblings() Method The siblings() method returns all sibling elements of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward and backwards along siblings of DOM elements.

How to get the child element of a parent using jQuery?

jQuery children() method is used to get the direct children of the selected HTML element. You can use children() method to traverse through the child elements of the selected parent element.


1 Answers

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); 
  }
}); 
like image 161
arnorhs Avatar answered Nov 05 '22 11:11

arnorhs