在jQuery中获取所有没有子节点的元素 [英] Get all elements without child node in jQuery

查看:115
本文介绍了在jQuery中获取所有没有子节点的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

示例:

标记:

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

脚本:

$("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.

推荐答案

如何

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

选择所有没有子项的跨度.

Selects all spans that have no children.

说明

:has() 选择器选择的元素至少包含一个与指定的选择器."通配符*表示所有元素.

如果<p>存在,则表达式$('div:has(p)')<div>匹配 它的后代中的任何地方,不仅是直子.

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

:not() 选择器选择与给定选择器不匹配的所有元素. "

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

在这种情况下,:has()选择所有内容,然后使用: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.

演示

这篇关于在jQuery中获取所有没有子节点的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆