How to choose twin parents
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 is this not working? I want to grab the value from the input and replace the contents of p .
You are referring to selectors for classes as if they were elements (they don't have a period:.) - so you probably want to change it to something like:
$(this).parent('.parent').siblings('.siblings').children('.children').html(addTo); but there are a bunch of other strange things that you also want to fix. Like others, you indicated that the if ( if($(this).siblings('input') != ""){ ) if($(this).siblings('input') != ""){ will always evaluate to true, I assume you are trying to find out if it is empty?
Here's a working full rewrite phrase:
$('button').click(function(){ var input = $(this).siblings('input'), val = input.val(); if(val != ""){ $(this).parent('.parent').find('.children').html(val); } }); The problem is the following lines:
Instead:
$(this).parent('parent').siblings('siblings').children('children').html(addTo); Try the following:
$(this).parent().siblings('.siblings').find('.children').html(addTo); Instead
$(this).siblings('input') != "" Try the following:
$(this).siblings('input').val() != "" You can do this bypassing the DOM (parents, children, and siblings), but I would recommend providing the identifiers of your elements so that they can be uniquely identified on the page.
Your current method is very fragile and will break if you change the structure of the page, while the method based on ID will not.