How to get the exact number of children with Javascript

时间:2015-09-30 23:19:47

标签: javascript parent-child

How to get all the children to an object when one of the children contains both properties of child1 and child2.

HTML:

<div id="parent1">
  <div class="child1"></div>
  <div class="child1 child2"></div>
  <div class="child2"></div>
  <div class="child2"></div>
</div>

Javascript:

var El = document.getElementById("parent1").children;
console.log(El.length);

The console shows the number 5. The number of elements I expected was 4.

1 个答案:

答案 0 :(得分:1)

对我来说,您的输入按预期返回4。我不知道你的文字有什么不同,但这里有一个小提琴:http://jsfiddle.net/rht670/9ayjvs4w/

&#13;
&#13;
var El = document.getElementById("parent1").children;
console.log(El.length);
&#13;
div {
    min-width: 100px;
    min-height: 100px;
    border: solid 1px black;
}
&#13;
<div id="parent1">
  <div class="child1"></div>
  <div class="child1 child2"></div>
  <div class="child2"></div>
  <div class="child2"></div>
</div>
&#13;
&#13;
&#13;