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
- Display message to every minute in Javascript
JavaScript - jQuery - Ajax
First post
Hello,
On eatch minute from the current hour I wanna have an message
I can not find out how to complete
I hope to get something like this (code...
Last post
If you only want to display a message to every minute, just use the setInterval() function. It calls a function repeatedly, over and over again, at...
- Hour and Minutes togheter in Javascript
JavaScript - jQuery - Ajax
First post
Dear Coursesweb I can not find out how to add the hours + minutes togheter.
<SCRIPT LANGUAGE= JavaScript >
day = new Date()
hr =...
Last post
See and use the following example:
<script>
var day = new Date();
let hr = day.getHours();
let mn = day.getMinutes();
let se =...