jQuery 获取jQuery中没有子节点的所有元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11061594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:08:16  来源:igfitidea点击:

Get all elements without child node in jQuery

jquery

提问by dpp

I need to select elements without child node (including text since in <p>text is a child node).

我需要选择没有子节点的元素(包括文本,因为<p>文本是子节点)。

I used empty, but it also consider space as child node.

我使用了empty,但它也将空间视为子节点。

Example:

例子:

Markup:

标记:

 <span> </span>
 <span></span>

Script:

脚本:

$("span:empty").html("this was empty!");

Unfortunately, only the second element were selected and changed since the first element has space and it was considered child node.

不幸的是,由于第一个元素有空间并且它被认为是子节点,因此只选择并更改了第二个元素。

How do I select elements without child node? I want to consider a space as nothing. Preferably, I want the code not to use loop to select them, there might be other ways.

如何选择没有子节点的元素?我想将空间视为虚无。最好,我希望代码不要使用循环来选择它们,可能还有其他方法。

回答by sachleen

How about

怎么样

$("span:not(:has(*))")

Selects all spans that have no children.

选择所有没有孩子的跨度。

Explanation

解释

The :has()selector "selects elements which contain at least one element that matches the specified selector." The wildcard *means all elements.

所述:has()选择器“它包含指定的选择器相匹配的至少一种元素选择的元素。” 通配符*表示所有元素。

The expression $('div:has(p)')matches a <div>if a <p>exists anywhere among its descendants, not just as a direct child.

如果 a存在于其后代中的任何位置,而不仅仅是作为直接子代,则表达式$('div:has(p)')匹配 a 。<div><p>

The :not()selector "selects all elements that do not match the given selector."

:not()选择“选择不与指定选择器匹配的所有元素。”

In this case, :has()selects everything and then we use :not()to find the elements that don't match "everything"... in other words, nothing.

在这种情况下,:has()选择所有内容,然后我们使用它:not()来查找与“所有内容”不匹配的元素……换句话说,什么都没有。

Demo

演示

回答by Esailija

$.expr[":"]["no-children"] = function( elem ) {
    return !elem.firstChild || !$.trim(""+ elem.firstChild.nodeValue);
};
$("span:no-children").html("this was empty");

?

?

http://jsfiddle.net/k5eTS/6/

http://jsfiddle.net/k5eTS/6/

There was a surprising "feature" with jQuery's $.trimthat converts nullto ""while I was expecting "null". Converting to string manually fixes this.

jQuery 有一个令人惊讶的“功能”,$.trim它在我期待的时候转换null为. 手动转换为字符串可解决此问题。"""null"

回答by thecodeparadox

I think you can try this:

我想你可以试试这个:

$('span').filter(function() {
   return !this.innerHTML.replace(/\s/g,'').length;
});

DEMO

演示

回答by thecodeparadox

Try this

尝试这个

$("span").each(function(){
if($(this).text().trim()=='')
$(this).text('Empty');
});

If you don't like each function then

如果你不喜欢每个功能,那么

$("span").html(function(){
if($(this).text().trim()=='')
return 'Empty';
});