ryanve ryanve - 2 months ago 7
Javascript Question

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

<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

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');
Comments