I have a really simple problem.
How can I find the first previous element of another element? I tried the code below without success.
HTML:
&
$('.C').click(function() {
alert($(this).closest('.B').prev('.A').html());
});
Try this:
$('.C').click(function() {
alert($(this).parent().prev('.A').html());
});
if you want to target closest children of top parent you can do so as something define below.
lets assume you have an HTML like
<div class="top-parent">
<div class="parent">
<button class="add-button">Child of 1st Parent DIV</button>
</div>
<div class="parent">
<button class="add-button">Child of 2nd Parent DIV</button>
</div>
</div>
<script>
$(document).on('click','.add-button',function(){
$(this).parents('.parent').prev().closest('.parent').find('.add-button').text('im clicked by one of the button next to my parent')
$(this).parents('.parent').remove();
})
</script>
similarly if you want to target grandparent next parent containers children just change .prev()
to .next()
hope i made it simple to define :)
If you are trying to get the preceding sibling, use .prev().
If you are trying to get the sibling of the parent (like in your example) use .parent().prev()
.