<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.
Use children. length to get the count of child 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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With