Welcome to my blog!

List all of the html id's in a document

April 28, 2021 17:11

List all of the html id's in a document (edit)

How do I enumerate all of the html id's in a document with javascript? - Stack Overflow

How to get all ID of the DOM elements with JavaScript ? - GeeksforGeeks

On modern browsers you can do this via


should do the job.

If you need all descendants of myElement with IDs, then do


If you want to be really careful to exclude <span id="">, then maybe


If compatibility with older browsers is required

var allElements = document.getElementsByTagName("*");
var allIds = [];
for (var i = 0, n = allElements.length; i < n; ++i) {
  var el = allElements[i];
  if (el.id) { allIds.push(el.id); }

should leave you with all the IDs in allIds.

If you find you need to just enumerate the IDs under a particular form node, then you can replace document.getElementsByTagName with myFormNode.getElementsByTagName.

If you want to include both IDs and NAMEs, then put

else if (el.name) { allIds.push(el.name); }

below the if above.


Recent posts