Getting HTML elements by their attribute names

后端 未结 7 653
南方客
南方客 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

    apple - no match
    onion - match
    root - match
    tomato - match
    

    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

提交回复
热议问题