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

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

How can you do the equivalent to

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

where query

8条回答
  •  一生所求
    2020-11-22 12:06

    A little modification on @kevinfahy 's answer, to allow getting the attribute by value if needed:

    function getElementsByAttributeValue(attribute, value){
      var matchingElements = [];
      var allElements = document.getElementsByTagName('*');
      for (var i = 0, n = allElements.length; i < n; i++) {
        if (allElements[i].getAttribute(attribute) !== null) {
          if (!value || allElements[i].getAttribute(attribute) == value)
            matchingElements.push(allElements[i]);
        }
      }
      return matchingElements;
    }
    

提交回复
热议问题