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
.
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".
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.
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.
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);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With