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

Solution 1:

On modern browsers you can do this via

document.querySelectorAll('*[id]')

should do the job.

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

myElement.querySelectorAll('*[id]')

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

document.querySelectorAll('*[id]:not([id=""])')

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.

Solution 2:

If you're doing your development using a fairly modern browser, you can use querySelectorAll(), then use Array.prototype.forEach to iterate the collection.

var ids = document.querySelectorAll('[id]');

Array.prototype.forEach.call( ids, function( el, i ) {
    // "el" is your element
    console.log( el.id ); // log the ID
});

If you want an Array of IDs, then use Array.prototype.map:

var arr = Array.prototype.map.call( ids, function( el, i ) {
    return el.id;
});

Solution 3:

The jQuery selector $('[id]') will get all the elements with an id attribute:

$('[id]').each(function () {
    do_something(this.id);
});

Working example here: http://jsfiddle.net/RichieHindle/yzMjJ/2/