ryanve ryanve - 1 year ago 73
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


where querySelectorAll is not available?

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

Answer Source

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.
  return matchingElements;


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download