[英]How to tell if an element is a child of another element in JavaScript (no jQuery)?
If I have 2 HTML elements, how can I easily tell if 1 is a child of the other? 如果我有2个HTML元素,我怎么能轻易判断1是否是另一个的孩子?
var parent = document.getElementById('shapes');
var child = document.getElementById('star');
Is there any kind of function on an element like child.getParentElement()
that I could compare with like child.getParentElement() == parent
? 有什么样的功能就像一个元素child.getParentElement()
是我能与喜欢比较child.getParentElement() == parent
?
I understand parent.children
gives me back an array of children, so I suppose I could use a for loop and compare each to child
. 我理解parent.children
给了我一系列的孩子,所以我想我可以使用for循环并将每个child
与child
进行比较。 Is there an easier single-function way to do this? 有没有更简单的单功能方式来做到这一点?
No jQuery or other libraries. 没有jQuery或其他库。
检查孩子的.parentNode
。
if (child.parentNode === parent) {...
There is parentNode
property within element
, so you can do following: element
有parentNode
属性,因此您可以执行以下操作:
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;
}
It will return true if parent
element is somewhere over child
element within DOM - not only when it's directly its parent. 如果parent
元素位于DOM中的child
元素之上,它将返回true - 不仅仅是它直接是它的父元素。
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: 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;
}
You can also use child.parentElement
to get parent. 您还可以使用child.parentElement
来获取父级。
I also Want to point out you can view all such properties in chrome web console
我还想指出您可以在chrome web console
查看所有此类属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.