Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - child node count

Tags:

<ul>     <li>Array1</li>     <li>Array2</li>     <li id="element">Array3</li> </ul> <script>    var temp = document.getElementById('element').parentNode;    child = temp.childNodes;    console.log(temp.length); </script> 

I need to get the child node length using element id. My code returns 7 as a result but I have only 3 nodes.

like image 694
Karthick V Avatar asked Aug 02 '12 11:08

Karthick V


People also ask

How do I count my child's node?

Use children. length to get the count of child node.

How do you get all the children of a node?

To get all child nodes of an element, you can use the childNodes property. This property returns a collection of a node's child nodes, as a NodeList object. By default, the nodes in the collection are sorted by their appearance in the source code.

What is a child node in JavaScript?

Child nodes include elements, text and comments. Note: The NodeList being live means that its content is changed each time new children are added or removed. The items in the collection of nodes are objects, not strings. To get data from node objects, use their properties.


1 Answers

childNodes gets all existing childNodes, including text nodes! In your example markup, you have your three "regular nodes" and 4 text nodes - the linebreaks - resulting in a total of 7 child nodes.

What you instead want is .children.length or .childElementCount (not supported in IE<9) to only fetch "actual" nodes:

let temp = document.getElementById('element').parentNode; console.log(temp.children.length); // or the following console.log(temp.childElementCount); 
like image 150
Christoph Avatar answered Oct 12 '22 01:10

Christoph