Getting HTML elements by their attribute names

后端 未结 7 620
南方客
南方客 2020-12-07 22:06

There are methods available in JavaScript to get HTML elements using their ID, Class and Tag.

document.getElementByID(*id*);
document.getElementsByClassName(         


        
相关标签:
7条回答
  • 2020-12-07 22:57

    Just another answer

    Array.prototype.filter.call(
        document.getElementsByTagName('span'),
        function(el) {return el.getAttribute('property') == 'v.name';}
    );
    

    In future

    Array.prototype.filter.call(
        document.getElementsByTagName('span'),
        (el) => el.getAttribute('property') == 'v.name'
    )
    

    3rd party edit

    Intro

    • The call() method calls a function with a given this value and arguments provided individually.

    • The filter() method creates a new array with all elements that pass the test implemented by the provided function.

    Given this html markup

    <span property="a">apple - no match</span>
    <span property="v:name">onion - match</span>
    <span property="b">root - match</span>
    <span property="v:name">tomato - match</span>
    <br />
    <button onclick="findSpan()">find span</button>
    

    you can use this javascript

    function findSpan(){
    
        var spans = document.getElementsByTagName('span');
        var spansV = Array.prototype.filter.call(
             spans,
             function(el) {return el.getAttribute('property') == 'v:name';}
        );
        return spansV;
    }
    

    See demo

    0 讨论(0)
提交回复
热议问题