Can I select multiple tags using getElementsByTagName?

后端 未结 4 613
天命终不由人
天命终不由人 2020-12-28 11:28

I\'m using a javascript snippet in order for visitors to my site to increase the font size on all paragraphs using the following javascript:

function increas         


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-28 12:02

    A year late, but if you intend on using the desired functionality multiple times in your project, and you don't have access to querySelector(), it might be worth extending the Node object with a simple function:

    JavaScript

    /**
     * @param {Array} tags - The array of tagNames to search for.
     * @return {Array}     - The elements with matching tagNames.
     */
    Node.prototype.getElementsByTagNames = function (tags) {
        var elements = [];
    
        for (var i = 0, n = tags.length; i < n; i++) {
            // Concatenate the array created from a HTMLCollection object
            elements = elements.concat(Array.prototype.slice.call(this.getElementsByTagName(tags[i])));
        }
    
        return elements;
    };
    

    Working demo on JSFiddle.

    All it does is iterating over an array of tag names, then getting the corresponding elements using getElementsByTagName() for each iteration.

    This can then of course be used on any element the same exact way you use similar functions - for example, getElementById() - on any Node object, you are not limited to document.

提交回复
热议问题