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

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

How can you do the equivalent to

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

where query

8条回答
  •  情深已故
    2020-11-22 11:55

    I played a bit around and ended up with this crude solution:

    function getElementsByAttribute(attribute, context) {
      var nodeList = (context || document).getElementsByTagName('*');
      var nodeArray = [];
      var iterator = 0;
      var node = null;
    
      while (node = nodeList[iterator++]) {
        if (node.hasAttribute(attribute)) nodeArray.push(node);
      }
    
      return nodeArray;
    }
    

    The usage is quite simple, and works even in IE8:

    getElementsByAttribute('data-foo');
    // or with parentNode
    getElementsByAttribute('data-foo', document);
    

    http://fiddle.jshell.net/9xaxf6jr/

    But I recommend to use querySelector / All for this (and to support older browsers use a polyfill):

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

提交回复
热议问题