get ALL id's of children elements

  • A+
Category:Languages

How do I get an array or something similar with ALL the id's of elements to a certain div?

Let's say I have someting like this:

<div id="parent-div">     <div id="div-no-1"></div>     <div id="div-no-2"></div>     <div id="div-no-3"></div>     <div id="div-no-4"></div> </div> 

I would then like an array that look's something like this

parent-div [     0: "div-no-1",     1: "div-no-2",     2: "div-no-3",     3: "div-no-3" ]; 

I've tried this...

$("#parent-div > div").attr("id"); 

...but it only gives me the first childs id, e.g. div-no-1. I want ALL of them

 


Use jQuery's each and push the id to the array:

var parentDiv = []; $("#parent-div > div").each((index, elem) => {   parentDiv.push(elem.id); });  console.log(parentDiv);
<script src="https://code.jquery.com/jquery-3.3.1.js"></script> <div id="parent-div">     <div id="div-no-1"></div>     <div id="div-no-2"></div>     <div id="div-no-3"></div>     <div id="div-no-4"></div> </div>

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: