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:
<div class = "A">HERE</div>
<div class="B">
<div class="C" style="width:50px;height:50px;background-color:#000000;"></div>
</div>
JS:
$('.C').click(function() {
alert($(this).closest('.A').html());
});
Fiddle: http://jsfiddle.net/Mcujp/4/
jQuery prev() Method The prev() method returns the previous sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse backwards along the previous sibling of DOM elements.
The prevAll() method returns all previous sibling elements of the selected element. Sibling elements are elements that share the same parent.
The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.
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()
.
Try this:
$('.C').click(function() {
alert($(this).parent().prev('.A').html());
});
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