简体   繁体   中英

jQuery for selecting tags that have a certain immediate child

How can I use jQuery to select all p tags that have at least one a tag as an immediate child?

For the document:

<div>
    <p><a>My Link</a></p>
    <p><div><a>My nested Link</a></div></p>
</div>

It would return only the first p tag.

I think you're probably going to have to use .filter() to do this. The following code should do what you need:

$('p').filter(function() { return $(this).children('a').length > 0;});

jsFiddle demo

EDIT: Modified the demo to include valid HTML (replaced the <div> with a <span> inside the second <p> ).

$('p:has(a)')

will do the trick.

http://jsfiddle.net/xKc8T/

Update

The issue with the font tag can be fixed like this:

$('a').parent('p')

http://jsfiddle.net/xKc8T/1/

Update 2

Okay scrap all that. As per the comments the :has() filter doesn't just look at the direct children. So how about we go the other way and select all a tags and then select the parent of those where the parent is a p .

 $('a').parent('p') 

or to avoid selecting all a tags you could do

$('p:has(> a)')

http://jsfiddle.net/xKc8T/3/

Yet Another Update

Thanks to @BoltClock for this suggestion. The following syntax also works:

 $('p:has(> a)') 

http://jsfiddle.net/xKc8T/4/

It's as easy as:

 $("div p:first-child") 

You might want to consider applying an id or a class to the div to limit the DOM traversal to just the relevant div and p blocks.

This answer is more or less the same thing , just looking for the last child.

UPDATE Sorry, misread the 'first p tag' bit.

Try this:

 $("div p:has(a)") 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM