Get Elements By Attribute

Benchmark created by MV on


Preparation HTML

<div class="fooClass" data-attr="fooAttr"></div>
<div class="fooClass"></div>
<div class="fooClass"></div>

Setup

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;
    }

Test runner

Ready to run.

Testing in
TestOps/sec
body
var nodes = document.body.querySelectorAll('[data-attr]');
ready
doc
var nodes = document.querySelectorAll('[data-attr]');
 
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.