如何检查元素在 Javascript 中是否有任何子元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2161634/
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
How to check if element has any children in Javascript?
提问by David
Simple question, I have an element which I am grabbing via .getElementById (). How do I check if it has any children?
简单的问题,我有一个元素,我通过.getElementById (). 我如何检查它是否有孩子?
回答by T.J. Crowder
A couple of ways:
几种方式:
if (element.firstChild) {
// It has at least one
}
or the hasChildNodes()function:
或hasChildNodes()功能:
if (element.hasChildNodes()) {
// It has at least one
}
or the lengthproperty of childNodes:
或length财产childNodes:
if (element.childNodes.length > 0) { // Or just `if (element.childNodes.length)`
// It has at least one
}
If you only want to know about child elements(as opposed to text nodes, attribute nodes, etc.) on all modern browsers (and IE8 — in fact, even IE6) you can do this: (thank you Florian!)
如果您只想了解所有现代浏览器(和 IE8 — 事实上,甚至 IE6)上的子元素(而不是文本节点、属性节点等),您可以这样做:(谢谢Florian!)
if (element.children.length > 0) { // Or just `if (element.children.length)`
// It has at least one element as a child
}
That relies on the childrenproperty, which wasn't defined in DOM1, DOM2, orDOM3, but which has near-universal support. (It works in IE6 and up and Chrome, Firefox, and Opera at leastas far back as November 2012, when this was originally written.) If supporting older mobile devices, be sure to check for support.
这依赖于children房地产,这是不是在定义DOM1,DOM2,或DOM3,但其中有接近普遍支持。(它在 IE6 及更高版本以及 Chrome、Firefox 和 Opera 中工作,至少可以追溯到 2012 年 11 月,当它最初编写时。)如果支持较旧的移动设备,请务必检查支持。
If you don't need IE8 and earlier support, you can also do this:
如果您不需要 IE8 及更早版本的支持,您也可以这样做:
if (element.firstElementChild) {
// It has at least one element as a child
}
That relies on firstElementChild. Like children, it wasn't defined in DOM1-3 either, but unlike childrenit wasn't added to IE until IE9.
这依赖于firstElementChild. 比如children,它也没有在 DOM1-3 中定义,但与childrenIE9 之前没有添加到 IE不同。
If you want to stick to something defined in DOM1 (maybe you have to support really obscure browsers), you have to do more work:
如果你想坚持在 DOM1 中定义的东西(也许你必须支持真正晦涩的浏览器),你必须做更多的工作:
var hasChildElements, child;
hasChildElements = false;
for (child = element.firstChild; child; child = child.nextSibling) {
if (child.nodeType == 1) { // 1 == Element
hasChildElements = true;
break;
}
}
All of that is part of DOM1, and nearly universally supported.
所有这些都是DOM1 的一部分,并且几乎得到普遍支持。
It would be easy to wrap this up in a function, e.g.:
将其包装在一个函数中会很容易,例如:
function hasChildElement(elm) {
var child, rv;
if (elm.children) {
// Supports `children`
rv = elm.children.length !== 0;
} else {
// The hard way...
rv = false;
for (child = element.firstChild; !rv && child; child = child.nextSibling) {
if (child.nodeType == 1) { // 1 == Element
rv = true;
}
}
}
return rv;
}
回答by c24w
As slashnick & bobince mention, hasChildNodes()will return true for whitespace (text nodes). However, I didn't want this behaviour, and this worked for me :)
正如 slashnick & bobince 所提到的,hasChildNodes()对于空白(文本节点)将返回 true。但是,我不想要这种行为,这对我有用:)
element.getElementsByTagName('*').length > 0
Edit: for the same functionality, this is a better solution:
编辑:对于相同的功能,这是一个更好的解决方案:
element.children.length > 0
children[]is a subset of childNodes[], containing elements only.
children[]是 的子集childNodes[],仅包含元素。
回答by slashnick
You can check if the element has child nodes element.hasChildNodes(). Beware in Mozilla this will return true if the is whitespace after the tag so you will need to verify the tag type.
您可以检查元素是否有子节点element.hasChildNodes()。当心在 Mozilla 中,如果标签后面是空格,这将返回 true,因此您需要验证标签类型。
回答by Danield
You could also do the following:
您还可以执行以下操作:
if (element.innerHTML.trim() !== '') {
// It has at least one
}
This uses the trim() method to treat empty elements which have only whitespaces (in which case hasChildNodesreturns true) as being empty.
这使用 trim() 方法将只有空格(在这种情况下hasChildNodes返回 true)的空元素视为空元素。
JSBin Demo
JSBin 演示
回答by Stirling
Try the childElementCount property:
if ( element.childElementCount !== 0 ){
alert('i have children');
} else {
alert('no kids here');
}
回答by K-Gun
Late but document fragment could be a node:
迟到但文档片段可能是一个节点:
function hasChild(el){
var child = el && el.firstChild;
while (child) {
if (child.nodeType === 1 || child.nodeType === 11) {
return true;
}
child = child.nextSibling;
}
return false;
}
// or
function hasChild(el){
for (var i = 0; el && el.childNodes[i]; i++) {
if (el.childNodes[i].nodeType === 1 || el.childNodes[i].nodeType === 11) {
return true;
}
}
return false;
}
See:
https://github.com/k-gun/so/blob/master/so.dom.js#L42
https://github.com/k-gun/so/blob/master/so.dom.js#L741
见:
https: //github.com/k-gun/so/blob/master/so.dom.js#L42
https://github.com/k-gun/so/blob/master/so.dom.js #L741
回答by Roko C. Buljan
A reusable isEmpty( <selector> )function.
You can also run it toward a collection of elements (see example)
一个可重用的isEmpty( <selector> )函数。
您还可以针对元素集合运行它(参见示例)
const isEmpty = sel =>
![... document.querySelectorAll(sel)].some(el => el.innerHTML.trim() !== "");
console.log(
isEmpty("#one"), // false
isEmpty("#two"), // true
isEmpty(".foo"), // false
isEmpty(".bar") // true
);
<div id="one">
foo
</div>
<div id="two">
</div>
<div class="foo"></div>
<div class="foo"><p>foo</p></div>
<div class="foo"></div>
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
returns true(and exits loop) as soon one element has any kind of content beside spaces or newlines.
true只要一个元素在空格或换行符旁边有任何类型的内容,就返回(并退出循环)。
回答by Govind Kumar Sahu
<script type="text/javascript">
function uwtPBSTree_NodeChecked(treeId, nodeId, bChecked)
{
//debugger;
var selectedNode = igtree_getNodeById(nodeId);
var ParentNodes = selectedNode.getChildNodes();
var length = ParentNodes.length;
if (bChecked)
{
/* if (length != 0) {
for (i = 0; i < length; i++) {
ParentNodes[i].setChecked(true);
}
}*/
}
else
{
if (length != 0)
{
for (i = 0; i < length; i++)
{
ParentNodes[i].setChecked(false);
}
}
}
}
</script>
<ignav:UltraWebTree ID="uwtPBSTree" runat="server"..........>
<ClientSideEvents NodeChecked="uwtPBSTree_NodeChecked"></ClientSideEvents>
</ignav:UltraWebTree>

