(jQuery) How do I find the first link which has a specific class?
If I have a link somewhere (not predetermined) down the tree like this:
<div id="foo">
<div>
<div>
<a href="asdf.com">link</a>
<a href="#bar" class="specialLink">link</a>
<a href="#bar2" class="specialLink">link</a>
<a href="#bar3" class="specialLink">link</a>
</div&g开发者_StackOverflow中文版t;
</div>
</div>
How would I go about selecting the first link with the class "specialLink" using .find()?
My non working guess is:
$("#foo").find(".specialLink a:first")
Just use one combined selector, like this:
$("#foo a.specialLink:first")
Or like your original:
$("#foo").find("a.specialLink:first")
Previously it was looking for the first <a>
that was a descendant of a .specialLink
, rather than the same element.
Your selector would be:
$("#foo").find("a.specialLink:first");
Better yet, save a few function calls by using:
$("$foo a.specialLink:first");
.specialLink
is the a itself. With a (space) :first
you will be looking for childeren of .specialLink
.
$("#foo").find("a.specialLink:first")
精彩评论