John Harrison John Harrison - 3 months ago 7
Javascript Question

Nested DIV tables (i.e. table within table), how to build an Object with all the data?

I am trying to build an object where each div row can have multiple sub rows

Please run this jsfiddle for the example
https://jsfiddle.net/h55bdxrf/18/

Thanks to jonas Ive got this far using children... so this is what comes out of childs[i] below

<div class=​"row chargePartyRow" id=​"1">
​<div class=​"col-sm-5 subDesc">​Sub Desc 1.1​</div>
​<div class=​"col-sm-5 colour">​Blue​</div>
​</div>​


but now final step how do I get the 1 from the id of the first div in the child?

<div class=​"row chargePartyRow" id=​"1">


I tried

console.log(childs[i].attr("id"));


but get I get the error: 'childs[i].attr is not a function'

Also want to get the ​'Sub Desc 1.1' and 'Blue' of the innerHtml

Answer

What you need is an array:

if you dont know, an array is a variable that holds multiple variables

var myobj={
children:[
     myobj2,
     myobj3
     ],
 description:"test"
 }

You can loop trough all of it with a selfcalling function

function check(obj,parent=window){
for(i=0;i<obj.children.length;i++){
check(obj.children[i],obj);
}
//do sth
}

Doing the same with the DOM:

function check(id){
//do whatever
parent=document.getElementById(id);
childs=parent.children;
for(i=0;i<childs.length;i++){
//do sth with the child
check(childs[i]);
}
}
Comments