Get elements by attribute when querySelectorAll is not available without using libraries?

ryanve picture ryanve · Feb 29, 2012 · Viewed 253.5k times · Source
<p data-foo="bar">

How can you do the equivalent to

document.querySelectorAll('[data-foo]')

where querySelectorAll is not available?

I need a native solution that works at least in IE7. I don’t care about IE6.

Answer

kevinfahy picture kevinfahy · Feb 29, 2012

You could write a function that runs getElementsByTagName('*'), and returns only those elements with a "data-foo" attribute:

function getAllElementsWithAttribute(attribute)
{
  var matchingElements = [];
  var allElements = document.getElementsByTagName('*');
  for (var i = 0, n = allElements.length; i < n; i++)
  {
    if (allElements[i].getAttribute(attribute) !== null)
    {
      // Element exists with attribute. Add to array.
      matchingElements.push(allElements[i]);
    }
  }
  return matchingElements;
}

Then,

getAllElementsWithAttribute('data-foo');