JavaScript - Get list with IDs of direct children
Posted: 25 Jan 2015, 17:15
Let say I have this html:
How can I get a list with the IDs of all the direct children in #parent, to result: ['c1', 'c2', 'c3'] (but not "c3_1")?
Also, to get the IDs of all the DIVs which are immediatelly in #parent, to result: ['c1', 'c3']?
I tryed this code, but I get also the children of child.
Code: Select all
<div id="parent">
<div id="c1">Content child 1</div>
<p id="c2">Paragraph ...
<span>some text</span>
</p>
<div id="c3">Child 3
<div id="c3_1">Child of Child</div>
</div>
Content in parent ...
</div>
Also, to get the IDs of all the DIVs which are immediatelly in #parent, to result: ['c1', 'c3']?
I tryed this code, but I get also the children of child.
Code: Select all
<script>
var chs = document.querySelectorAll('#parent div');
var ids = [];
for(var i=0; i<chs.length; i++) {
ids[i] = chs[i].id;
}
console.log(ids); // ["c1", "c3", "c3_1"]
</script>