To get all HTML element IDs with jQuery, we just have to select all the elements and then we can get the id
property from each element.
For instance, if we have the following HTML:
<div id="mydiv">
<span id='span1'></span>
<span id='span2'></span>
</div>
Then we can get the IDs of all the span elements by writing:
const ids = [...$("#mydiv").find("span")].map(s => s.id);
console.log(ids)
We get all the spans with:
$("#mydiv").find("span")
Then we convert the returned nodelist into an array with the spread operator.
And then we call the JavaScript array map
method it the returned array with a callback that returns the id
from the s
span element.
Therefore ids
is [“span1”, “span2”]
.