How to Get All HTML Element IDs with JavaScript?

Sometimes, we want to get all HTML element IDs with JavaScript.

In this article, we’ll look at how to get all HTML element IDs with JavaScript.

Get All HTML Element IDs with JavaScript

To get all HTML element IDs with JavaScript, 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”] .

Conclusion

To get all HTML element IDs with JavaScript, we just have to select all the elements and then we can get the id property from each element.