[英]Selecting <p> elements that have not text nodes in jQuery
我有这个HTML结构:
<div class="article-body">
<p>
<a href="http://www.example.com">My Link</a>
Lorem Ipsum Dolor Sit amet.
</p>
<p><a href="http://www.example.com">Link that I must select.</a></p>
</div>
我必须将一个类应用于第二个链接,一个没有文本节点的链接。 我试过“p:empty a”和“p> a:only-child”但是它们不起作用...有一种方法可以使用jQuery选择它吗?
不能用选择器,但你可以使用filter()
来执行自定义选择:
$('p').filter(function(){
var $clone = $(this).clone();
$clone.children().remove();
return !$clone.text();
}).addClass("red");
在这里,有一个小提琴: http : //jsfiddle.net/adrianonantua/5daYT/
:)
更新
根据@dfsq建议,我们可以利用end()
并在同一行中创建相同的逻辑:
$('p').filter(function(){
return !$(this).clone().children().remove().end().text();
}).addClass("red");
filter()
另一个解决方案:
$("p").filter(function() {
return $(this).contents().filter(function() {
return this.nodeType == 3 && $.trim(this.nodeValue) != "";
}).length == 0;
}).addClass("myClass");
演示: http : //jsfiddle.net/wyvLC/
这将是一个非常快速的解决方案。 无需克隆:
$("p > a").filter(function(i, el) {
return !el.previousSibling && !el.nextSibling;
}).parent();
或这个:
$("p").filter(function(i, el) {
return el.firstChild &&
el.firstChild === el.lastChild &&
el.firstChild.nodeName.toUpperCase() === "A";
});
这应该工作http://jsfiddle.net/nvass/ :
$("p").filter(function(){
return $.grep(this.childNodes,function(node){
return node.nodeType === 3 && node.nodeValue.replace(/(\s|\n|\r|\t)/g,"") !== "";
}).length === 0;
}).css("background-color","green");
或者你可以使用单行: $("p").filter(function(){ return $(this).clone().children().remove().end().text() == ""; });
...
演示: http : //jsfiddle.net/bJnEJ/1/
来源(改编): http : //viralpatel.net/blogs/jquery-get-text-element-without-child-element/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.