I want to get the previous element that is closest to the .me element filtering it by a .a class.This script returns me undefined..Why it’s returning me undefined and how do I fix this?
<p class="a" id="a1">Hello Again</p>
<div class="a" id="a2">And Again</div>
<p id="a3">And Again</p>
<p class="me">And Again</p>
</div>
<script>
alert($(".me").prev("p.a").attr("id"));
</script>
The
prev()[docs] method only looks at the immediate sibling.Use the
prevAll()[docs] method instead to consider all previous siblings.The
attr()[docs] method will give the ID of the first matched element, which is the nearest.If you want to be more explicit in selecting the nearest one, use the
first()[docs] method or theeq()[docs] method.