如何检查Element的孩子是否也包含孩子

时间:2018-08-02 14:25:37

标签: javascript html

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

如果容器具有以下内容:

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

2 个答案:

答案 0 :(得分:1)

在显示的代码的第一部分中,没有父子关系,但有兄弟姐妹关系:https://www.w3schools.com/jsref/prop_node_nextsibling.asp

代码的第二部分,您有一个span(带有classEntityHighlight类),其中包含三个元素span(子元素)。您可以使用: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>

答案 1 :(得分:0)

您应该寻找contains()方法:https://www.w3schools.com/jsref/met_node_contains.asp

  

contains()方法返回一个布尔值,该值指示节点是否为指定节点的后代。

     

后代可以是孩子,孙子,曾孙等等。

示例:

<div id="myDIV">
    <span id="mySPAN">
    </span>
</div>

var span = document.getElementById("mySPAN");
var div = document.getElementById("myDIV").contains(span);