gpt4 book ai didi

javascript - 如何检查元素的 child 是否也包含 child

转载 作者:行者123 更新时间:2023-11-30 20:18:56 26 4
gpt4 key购买 nike

那么,如何检查容器中的子元素是否也有child,

如果容器的内容是这样的:

var container = document.createElement("span");

<span name="70" onmousedown="top.onMouseDownEssence('70','');" onmouseup="top.onMouseUpEssence('70','');"></span>
<span name="70" onmousedown="top.onMouseDownEssence('70','');" onmouseup="top.onMouseUpEssence('70','');">s</span>
<span name="70" onmousedown="top.onMouseDownEssence('70','');" onmouseup="top.onMouseUpEssence('70','');">o</span>
<span name="70" onmousedown="top.onMouseDownEssence('70','');" onmouseup="top.onMouseUpEssence('70','');">u</span>

它应该返回 false,因为所有子元素都在同一级别。如果容器有这样的内容:

<span class="entityHighlight">
<span name="70" onmousedown="top.onMouseDownEssence('70','');" onmouseup="top.onMouseUpEssence('70','');">s</span>
<span name="70" onmousedown="top.onMouseDownEssence('70','');" onmouseup="top.onMouseUpEssence('70','');">o</span>
<span name="70" onmousedown="top.onMouseDownEssence('70','');" onmouseup="top.onMouseUpEssence('70','');">u</span>
</span>

我需要返回true,因为它有父子关系。

最佳答案

在您显示的第一部分代码中,没有父子关系,而是 sibling 关系:https://www.w3schools.com/jsref/prop_node_nextsibling.asp

代码的第二部分,您有一个跨度(具有类 entityHighlight),它包含三个元素跨度(子级)。您可以使用:https://www.w3schools.com/jsref/met_node_haschildnodes.asp

var container = document.getElementById("container");

var spans = container.getElementsByTagName("span");

console.log("First Span: " + spans[0].innerHTML);
console.log("Next Sibling Span: " + spans[0].nextElementSibling.innerHTML);

console.log("Does first span as element children: " + (spans[0].children.length > 0));

console.log("Does first span as node children: " + spans[0].hasChildNodes());

var isAnyOfTheseNodesAnElement = false;
for (var node in spans[0].childNodes){
if (node instanceof Element){
isAnyOfTheseNodesAnElement = true;
}
}
console.log("Is any of those node children an element? " + isAnyOfTheseNodesAnElement);



console.log("--------------------------------------------------------------------");

var spanEntity = document.getElementsByClassName("entityHighlight")[0];
console.log("Does the spanEntity span has element children: " + (spanEntity.children.length > 0));

for (var i = 0; i < spanEntity.children.length; ++i){
console.log("Child " + i + ": " + spanEntity.children[i].innerHTML);
}
<div id="container">

<span name="70">A</span>
<span name="70">B</span>
<span name="70">C</span>
<span name="70">D</span>

<span class="entityHighlight">
<span name="70">E</span>
<span name="70">F</span>
<span name="70">G</span>
</span>

</div>

关于javascript - 如何检查元素的 child 是否也包含 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51656047/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com