How to get the least previous element filtering it by class?
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("i开发者_如何学God"));
</script>
The prev()
[docs] method only looks at the immediate sibling.
Use the prevAll()
[docs] method instead to consider all previous siblings.
$(".me").prevAll("p.a").attr("id")
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 the eq()
[docs] method.
$(".me").prevAll("p.a").first().attr("id")
$(".me").prevAll("p.a").eq( 0 ).attr("id")
精彩评论