Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive function to find children count in javascript

Tags:

javascript

How can I find out the total children count of each root node P in my JSON object. This is not a DOM structure. Considering P2 's children also children of P1 as P2 is child of P1.

P1-|-C1            (P1 children count 3)
   |-C2
   |-P2-|-C1       (P2 children count 5)
        |-C2
        |-P3-|-C1  (P3 children count 2)
             |-C2
        |-C3
        |-C4
        |-P4-|-C1   (P4 children count 2)
             |-C2

Thanks in advance.

like image 701
Tarak Avatar asked Sep 15 '25 10:09

Tarak


1 Answers

It's fairly simple without any library or custom code.

//Or whatever way you want to grab a reference to the DOM node
var p1 = document.getElementById('P1');

p1.getElementsByTagName('*').length

Maybe I misunderstood the question. Is this what you want?:

p1.childNodes.length
like image 85
Prinzhorn Avatar answered Sep 16 '25 23:09

Prinzhorn