简体   繁体   English

jQuery用于选择具有特定直接子项的标签

[英]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? 如何使用jQuery选择至少有一个标签作为直接子项的所有p标签?

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. 它只返回第一个p标签。

I think you're probably going to have to use .filter() to do this. 我想你可能不得不使用.filter()来做这件事。 The following code should do what you need: 以下代码应该满足您的需求:

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

jsFiddle demo jsFiddle演示

EDIT: Modified the demo to include valid HTML (replaced the <div> with a <span> inside the second <p> ). 编辑:修改了演示,以包括有效的HTML(取代<div><span>第二内侧<p>

$('p:has(a)') $( 'P:有(一)')

will do the trick. 会做的。

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

Update 更新

The issue with the font tag can be fixed like this: font标记的问题可以修复如下:

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

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

Update 2 更新2

Okay scrap all that. 好吧废弃所有这些。 As per the comments the :has() filter doesn't just look at the direct children. 根据评论:has()过滤器不只是看直接子项。 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标签,然后选择那些母公司如果母公司是p

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

or to avoid selecting all a tags you could do 或避免选择所有的a标签,你可以做

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

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

Yet Another Update 又一次更新

Thanks to @BoltClock for this suggestion. 感谢@BoltClock提出这个建议。 The following syntax also works: 以下语法也有效:

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

http://jsfiddle.net/xKc8T/4/ 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. 您可能要考虑申请一个idclassdiv的DOM遍历限制为仅相关divp块。

This answer is more or less the same thing , just looking for the last child. 这个答案或多或少都是一样的 ,只是寻找最后一个孩子。

UPDATE Sorry, misread the 'first p tag' bit. 更新对不起,误读了'第一个p标签'位。

Try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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