如果一个元素包含在另一个元素中,如何检查 Javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2234979/
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 in Javascript if one element is contained within another
提问by AJ.
How can I check if one DOM element is a child of another DOM element? Are there any built in methods for this? For example, something like:
如何检查一个 DOM 元素是否是另一个 DOM 元素的子元素?是否有任何内置方法?例如,类似于:
if (element1.hasDescendant(element2))
or
或者
if (element2.hasParent(element1))
If not then any ideas how to do this? It also needs to be cross browser. I should also mention that the child could be nested many levels below the parent.
如果没有,那么任何想法如何做到这一点?它还需要跨浏览器。我还应该提到,子级可以嵌套在父级之下许多级别。
回答by Brian Di Palma
You should use Node.contains, since it's now standard and available in all browsers.
您应该使用Node.contains,因为它现在是标准的并且在所有浏览器中都可用。
https://developer.mozilla.org/en-US/docs/Web/API/Node.contains
https://developer.mozilla.org/en-US/docs/Web/API/Node.contains
回答by Asaph
Update:There's now a native way to achieve this. Node.contains(). Mentioned in comment and below answers as well.
更新:现在有一种本地方式来实现这一点。Node.contains(). 在评论和下面的答案中也提到了。
Old answer:
旧答案:
Using the parentNodeproperty should work. It's also pretty safe from a cross-browser standpoint. If the relationship is known to be one level deep, you could check it simply:
使用该parentNode属性应该有效。从跨浏览器的角度来看,它也非常安全。如果已知该关系深一层,您可以简单地检查它:
if (element2.parentNode == element1) { ... }
If the the child can be nested arbitrarily deep inside the parent, you could use a function similar to the following to test for the relationship:
如果子级可以任意嵌套在父级内部,则可以使用类似于以下的函数来测试关系:
function isDescendant(parent, child) {
var node = child.parentNode;
while (node != null) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
}
回答by GitaarLAB
I just had to share 'mine'.
我只需要分享“我的”。
Although conceptually the same as Asaph's answer(benefiting from the same cross-browser compatibility, even IE6), it is a lotsmaller and comes in handy when size is at a premium and/or when it is not needed so often.
虽然概念一样亚萨的答案(受益于相同的跨浏览器的兼容性,甚至IE6),这是一个很多更小,非常适合对尺寸为溢价和/或当它不需要经常。
function childOf(/*child node*/c, /*parent node*/p){ //returns boolean
while((c=c.parentNode)&&c!==p);
return !!c;
}
..or as one-liner (just 64 chars!):
..或作为单行(仅 64 个字符!):
function childOf(c,p){while((c=c.parentNode)&&c!==p);return !!c}
and jsfiddle here.
Usage:childOf(child, parent)returns boolean true|false.
用法:childOf(child, parent)返回布尔值true| false.
Explanation:whileevaluates as long as the while-condition evaluates to true.
The &&(AND) operator returns this boolean true/false afterevaluating the left-hand side and the right-hand side, but only ifthe left-hand side was true (left-hand && right-hand).
说明:while只要 while 条件的计算结果为true。
该&&(AND)运算符返回此布尔真/假后评估的左侧和右侧,但只有当左手侧是真实的(left-hand && right-hand)。
The left-hand side (of &&) is: (c=c.parentNode).
This will first assign the parentNodeof cto cand then the AND operator will evaluate the resulting cas a boolean.
Since parentNodereturns nullif there is no parent left and nullis converted to false, the while-loop will correctly stop when there are no more parents.
左侧(的&&)是:(c=c.parentNode)。
这将首先将parentNodeof分配c给c,然后 AND 运算符会将结果评估c为布尔值。
由于如果没有父节点而parentNode返回null并null转换为false,那么当没有更多父节点时,while 循环将正确停止。
The right-hand side (of &&) is: c!==p.
The !==comparison operator is 'notexactly equal to'. So if the child's parent isn't the parent (you specified) it evaluates to true, but if the child's parent isthe parent then it evaluates to false.
So ifc!==pevaluates to false, then the &&operator returns falseas the while-condition and the while-loop stops. (Note there is no need for a while-body and the closing ;semicolon is required.)
右侧(的&&)是:c!==p。
的!==比较操作符是“不完全等于”。因此,如果孩子的父母不是父母(您指定的),则其计算结果为true,但如果孩子的父母是父母,则计算结果为false。
因此,如果c!==p计算结果为 false,则&&运算符false作为 while 条件返回,while 循环停止。(注意不需要 while-body 并且;需要结束分号。)
So when the while-loop ends, cis either a node (not null) when it found a parent OR it is null(when the loop ran through to the end without finding a match).
因此,当 while 循环结束时,c它要么是一个节点(不是null),要么是它找到父节点时,要么是null(当循环运行到最后而没有找到匹配项时)。
Thus we simply returnthat fact (converted as boolean value, instead of the node) with: return !!c;: the !(NOToperator) inverts a boolean value (truebecomes falseand vice-versa).!cconverts c(node or null) to a boolean before it can invert that value. So adding a second !(!!c) converts this false backto true (which is why a double !!is often used to 'convert anything to boolean').
因此,我们简单地将return这个事实(转换为布尔值,而不是节点)与:return !!c;: !(NOT运算符)反转布尔值(true成为false和反之亦然)。在它可以反转该值之前!c将c(节点或空)转换为布尔值。因此,添加第二个!( !!c) 会将这个 false 转换回true(这就是为什么!!经常使用double来“将任何内容转换为布尔值”)。
Extra:
The function's body/payload is so small that, depending on case (like when it is not used often and appears just once in the code), one couldeven omit the function (wrapping) and just use the while-loop:
额外:
该函数的主体/有效负载非常小,根据情况(例如,当它不经常使用并且在代码中只出现一次时),甚至可以省略该函数(包装)而只使用 while 循环:
var a=document.getElementById('child'),
b=document.getElementById('parent'),
c;
c=a; while((c=c.parentNode)&&c!==b); //c=!!c;
if(!!c){ //`if(c)` if `c=!!c;` was used after while-loop above
//do stuff
}
instead of:
代替:
var a=document.getElementById('child'),
b=document.getElementById('parent'),
c;
function childOf(c,p){while((c=c.parentNode)&&c!==p);return !!c}
c=childOf(a, b);
if(c){
//do stuff
}
回答by Josh Crozier
Another solution that wasn't mentioned:
另一个没有提到的解决方案:
var parent = document.querySelector('.parent');
if (parent.querySelector('.child') !== null) {
// .. it's a child
}
It doesn't matter whether the element is a direct child, it will work at any depth.
元素是否是直接子元素并不重要,它可以在任何深度工作。
Alternatively, using the .contains()method:
或者,使用.contains()方法:
var parent = document.querySelector('.parent'),
child = document.querySelector('.child');
if (parent.contains(child)) {
// .. it's a child
}
回答by Josh Crozier
Take a look at Node#compareDocumentPosition.
看看Node#compareDocumentPosition。
function isDescendant(ancestor,descendant){
return ancestor.compareDocumentPosition(descendant) &
Node.DOCUMENT_POSITION_CONTAINS;
}
function isAncestor(descendant,ancestor){
return descendant.compareDocumentPosition(ancestor) &
Node.DOCUMENT_POSITION_CONTAINED_BY;
}
Other relationships include DOCUMENT_POSITION_DISCONNECTED, DOCUMENT_POSITION_PRECEDING, and DOCUMENT_POSITION_FOLLOWING.
其他关系包括DOCUMENT_POSITION_DISCONNECTED,DOCUMENT_POSITION_PRECEDING,和DOCUMENT_POSITION_FOLLOWING。
Not supported in IE<=8.
IE<=8 不支持。
回答by Iegor Kozakov
You can use the contains method
您可以使用contains 方法
var result = parent.contains(child);
var result = parent.contains(child);
or you can try to use compareDocumentPosition()
或者你可以尝试使用compareDocumentPosition()
var result = nodeA.compareDocumentPosition(nodeB);
var result = nodeA.compareDocumentPosition(nodeB);
The last one is more powerful: it return a bitmask as result.
最后一个更强大:它返回一个位掩码作为结果。
回答by RashFlash
I came across a wonderful piece of code to check whether or not an element is a child of another element. I have to use this because IE doesn't support the .containselement method. Hope this will help others as well.
我遇到了一段很棒的代码来检查一个元素是否是另一个元素的子元素。我必须使用它,因为 IE 不支持.contains元素方法。希望这也能帮助其他人。
Below is the function:
下面是函数:
function isChildOf(childObject, containerObject) {
var returnValue = false;
var currentObject;
if (typeof containerObject === 'string') {
containerObject = document.getElementById(containerObject);
}
if (typeof childObject === 'string') {
childObject = document.getElementById(childObject);
}
currentObject = childObject.parentNode;
while (currentObject !== undefined) {
if (currentObject === document.body) {
break;
}
if (currentObject.id == containerObject.id) {
returnValue = true;
break;
}
// Move up the hierarchy
currentObject = currentObject.parentNode;
}
return returnValue;
}
回答by user3675072
try this one:
试试这个:
x = document.getElementById("td35");
if (x.childElementCount > 0) {
x = document.getElementById("LastRow");
x.style.display = "block";
}
else {
x = document.getElementById("LastRow");
x.style.display = "none";
}

