JavaScript - Get list with IDs of direct children

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
PloMar
Posts: 48

JavaScript - Get list with IDs of direct children

Let say I have this html:

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>
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

<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>

Admin Posts: 805
Try with the ">" selector, it refers to the direct childen.
1. Example get array with the ID of all direct children.

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>

<script>
var chs = document.querySelectorAll('#parent > *');
var ids = [];
for(var i=0; i<chs.length; i++) {
  ids[i] = chs[i].id;
}

console.log(ids);    // ["c1", "c2", "c3"]
</script>
2. Example get array with the IDs of all immediately children DIV.

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"]
</script>
3. All the DIVs with class="cls" which are direct children of #parent : "#parent > div.cls".

Similar Topics