2

如果我有 2 个 HTML 元素,如何轻松判断 1 是否是另一个的子元素?

var parent = document.getElementById('shapes');
var child = document.getElementById('star');

child.getParentElement()我可以与 like 比较的元素上是否有任何类型的功能child.getParentElement() == parent

我知道parent.children给了我一组孩子,所以我想我可以使用 for 循环并将每个与child. 有没有更简单的单功能方法来做到这一点?

没有 jQuery 或其他库。

4

4 回答 4

8

检查.parentNode孩子的情况。

if (child.parentNode === parent) {...
于 2013-04-07T19:58:04.173 回答
2

内有parentNode属性element,因此您可以执行以下操作:

var parent = document.getElementById('shapes');
var child = document.getElementById('star');

var isChild = false;
var current = child;
while(current = current.parentNode)
{
    if(current == parent)
        isChild = true;
}

parent如果元素位于 DOM 中的某个元素之上,它将返回 true child- 不仅是当它直接是其父元素时。

于 2013-04-07T19:59:26.587 回答
1

If you need only the direct child from parent element, take a look at below example:

<div id="div1">
    Parent
    <div id="div2">
        Child
        <div id="div3-1">
            N-child 1
        </div>
        <div id="div3-2">
            N-child 2
        </div>
    </div>
</div>
<input type="button" id="btn-action" value="Run" />
<div id="result"></div>

JavaScript:

document.getElementById("btn-action").addEventListener("click",function(e) {
    var div1 = document.getElementById("div1"),
        div2 = document.getElementById("div2"),
        nchild1 = document.getElementById("div3-1"),
        nchild2 = document.getElementById("div3-2");

    document.getElementById("result").innerHTML =
        "<br/>div2 is child of div1? - " + fnIsChild(div1, div2) + 
        "<br/>div3-1 is child of div1? - " + fnIsChild(div1, nchild1) + 
        "<br/>div3-2 is child of div1? - " + fnIsChild(div1, nchild1);
});

function fnIsChild(parentElem, childElem) {
    var childNodes = parentElem.childNodes,
        max = childNodes.length,
        n;
    for(n = 0; n < max; n += 1) {
        if(childNodes[n] === childElem) return true;
    }
    return false;
}
于 2013-04-08T00:20:08.397 回答
0

You can also use child.parentElement to get parent.

I also Want to point out you can view all such properties in chrome web console

enter image description here

于 2013-04-07T20:08:09.877 回答