jQuery selector: all links in first paragraph
I would like t开发者_开发百科o apply doSomething() to every link of the first paragraph, using jQuery. This is what I have tried:
var firstParagraph = $("p").eq(0);
firstParagraph.$("a").doSomething();
What's the correct format? (P.S. Where can I learn about such selectors in more depth?)
You can also do:
var anchors = $('p:first a');
And there's more on selectors here:
http://api.jquery.com/category/selectors/
firstParagraph.find("a").doSomething();
Also you might use shorthand:
var links = $("p:first a");
The easiest way to do precise element selection is with the CSS selectors inside of $(...)
. For instance, to hide all links in the first paragraph, do this
$('p:first-child a').hide();
But watch out, this will hide probably more than you want. It would affect the first paragraph in any div
, for instance. If you want to hide only the first paragraph of the HTML body and not first paragraphs of subelements of the page, do either of these
$('body > p:first-child a').hide(); // first paragraph in body
$('p:first a').hide(); // first paragraph anywhere, but only once
These selectors (except :first
) are jQuery agnostic. You can read about them here.
精彩评论