如何检查一个元素是否有特定的孩子?如何检查元素是否有特定的孩子?
var child1 = document.createElement('div');
document.body.appendChild(child1);
如何检查是否child1
已连接到body
:
我用孩子加入到我的元素?
if (document.body.alreadyHas(child1)) …
^^^^^^^^^^
what to do here?
如何检查一个元素是否有特定的孩子?如何检查元素是否有特定的孩子?
var child1 = document.createElement('div');
document.body.appendChild(child1);
如何检查是否child1
已连接到body
:
我用孩子加入到我的元素?
if (document.body.alreadyHas(child1)) …
^^^^^^^^^^
what to do here?
两个因素考虑引用,您可以测试是否一个是另一个的孩子使用.parentElement
property如下:
if (child1.parentElement === parent1) {
// do something
}
在你所说的父您的具体情况
所以是body
,你可以这样做:
var child1 = document.createElement('div');
var child2 = document.createElement('div');
document.body.appendChild(child1); // note we only append one
if (child1.parentElement === document.body) {
console.log("child1 is a child of the body"); // this will run
}
if (child2.parentElement === document.body) {
console.log("child2 is a child of the body"); // this won't run
}
最后,我得到了一些工作,并简单理解!万分感谢。 – Shalom
分享您的代码 – brk
那么至少告诉我们你在找什么 – mean
分享你的代码。 – Ray