我如何获取div中的所有id名称

如何获取div中的所有id名称并将其推入数组中?

//elements
<div id="container">
     <div id="number1"></div>
     <div id="number2"></div>
     <div id="number3"></div>
</div>

//fetch id names
while (thereAreIdNamesInsideDiv){
    array.push(idName)
}

//the array
array["number1", "number2", "number3"]

评论
  • qet
    qet 回复

    You can use querySelectorAll and map which will return an array. Inside map callback use getAttribute to get the element id

    const arr = [...document.getElementById('container').querySelectorAll('div')]
    .map(item => item.getAttribute('id'));
    console.log(arr)
    <div id="container">
      <div id="number1"></div>
      <div id="number2"></div>
      <div id="number3"></div>
    </div>