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

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

How can you do the equivalent to

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

where query

8条回答
  •  执笔经年
    2020-11-22 11:44

    Don't use in Browser

    In the browser, use document.querySelect('[attribute-name]').

    But if you're unit testing and your mocked dom has a flakey querySelector implementation, this will do the trick.

    This is @kevinfahy's answer, just trimmed down to be a bit with ES6 fat arrow functions and by converting the HtmlCollection into an array at the cost of readability perhaps.

    So it'll only work with an ES6 transpiler. Also, I'm not sure how performant it'll be with a lot of elements.

    function getElementsWithAttribute(attribute) {
      return [].slice.call(document.getElementsByTagName('*'))
        .filter(elem => elem.getAttribute(attribute) !== null);
    }
    

    And here's a variant that will get an attribute with a specific value

    function getElementsWithAttributeValue(attribute, value) {
      return [].slice.call(document.getElementsByTagName('*'))
        .filter(elem => elem.getAttribute(attribute) === value);
    }
    

提交回复
热议问题