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

后端 未结 8 923
半阙折子戏
半阙折子戏 2020-11-22 11:27

How can you do the equivalent to

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

where query

8条回答
  •  轮回少年
    2020-11-22 12:08

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

提交回复
热议问题