且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查元素中是否有任何孩子在Javascript?

更新时间:2023-11-28 23:34:22

有几种方法:

if (element.firstChild) {
    // It has at least one
}

hasChildNodes()功能:

if (element.hasChildNodes()) {
    // It has at least one
}

长度属性 childNodes

if (element.childNodes.length > 0) { // Or just `if (element.childNodes.length)`
    // It has at least one
}

如果你只想知道孩子所有现代浏览器(和IE8实际上甚至IE6)中的元素(而不是文本节点,属性节点等)可以这样做:(谢谢 Florian !)

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!)

if (element.children.length > 0) { // Or just `if (element.children.length)`
    // It has at least one element as a child
}

依赖于 儿童 属性,未在 DOM1 DOM2 DOM3 ,但具有近乎普遍的支持。 (它最早在2012年11月,IE6及以上版本的Chrome,Firefox和Opera版本最少)。如果支持较旧的移动设备,请确保支持。

That relies on the children property, which wasn't defined in DOM1, DOM2, or DOM3, but which has near-universal support. (It works in IE6 and up and Chrome, Firefox, and Opera at least as far back as November 2012, when this was originally written.) If supporting older mobile devices, be sure to check for support.

如果您不需要IE8及更早版本的支持,您还可以执行以下操作:

If you don't need IE8 and earlier support, you can also do this:

if (element.firstElementChild) {
    // It has at least one element as a child
}

这依赖于 firstElementChild 。喜欢 children ,它没有在DOM1-3中定义,但不同于 children 它没有添加到IE直到IE9。

That relies on firstElementChild. Like children, it wasn't defined in DOM1-3 either, but unlike children it wasn't added to IE until IE9.

如果你想坚持在DOM1中定义的东西(也许你必须支持真正模糊的浏览器),你必须做更多的工作:

If you want to stick to something defined in DOM1 (maybe you have to support really obscure browsers), you have to do more work:

var hasChildElements, child;
hasChildElements = false;
for (child = element.firstChild; child; child = child.nextSibling) {
    if (child.nodeType == 1) { // 1 == Element
        hasChildElements = true;
        break;
    }
}

所有这些都是 DOM1 ,几乎被普遍支持。

All of that is part of DOM1, and nearly universally supported.

将它放在一个函数中很容易,例如:

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;
}