因此,如何检查容器中的子元素是否也有子元素,

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

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,因为它具有父子关系。

最佳答案

在显示的代码的第一部分中,没有父子关系,但有兄弟姐妹关系: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 - 如何检查Element的 child 是否也包含 child ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51656047/

10-09 22:02