简体   繁体   中英

How to get the exact number of children with Javascript

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.

For me, your input returned 4, as expected. I don't know what is different from your text though, but here is a fiddle: http://jsfiddle.net/rht670/9ayjvs4w/ .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM