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

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

How can you do the equivalent to

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

where query

相关标签:
8条回答
  • 2020-11-22 12:09

    Try this it works

    document.querySelector('[attribute="value"]')

    example :

    document.querySelector('[role="button"]')
    
    0 讨论(0)
  • 2020-11-22 12:09

    Try this - I slightly changed the above answers:

    var getAttributes = function(attribute) {
        var allElements = document.getElementsByTagName('*'),
            allElementsLen = allElements.length,
            curElement,
            i,
            results = [];
    
        for(i = 0; i < allElementsLen; i += 1) {
            curElement = allElements[i];
    
            if(curElement.getAttribute(attribute)) {
                results.push(curElement);
            }
        }
    
        return results;
    };
    

    Then,

    getAttributes('data-foo');
    
    0 讨论(0)
提交回复
热议问题