Can I select multiple tags using getElementsByTagName?

后端 未结 4 616
天命终不由人
天命终不由人 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:19

    to select two tags at once? Yes we can create one loop for both at once.
    This is your whole example. But one loop (one array) with both P and LI:

    function increaseFontSize() {  
    
        Array.from(document.getElementsByTagName('p'))
            .concat(Array.from(document.getElementsByTagName('li'))).forEach(el => {
    
    
                if(el.style.fontSize) { 
                    var s = parseInt(el.style.fontSize.replace("px",""));
                } else {   
                    var s = 14;
                }
    
                if(s != max) {  
                    s += 1; 
                } 
                el.style.fontSize = s+"px"
        });
    } 
    

    Explanation:
    Array.from()
    this is official way how to make real Array from a collection.
    Some browsers might support forEach on HTMLCollection but it's not in specs.
    Even so, they probably don't support concat() method.
    Using from() will create a shallow copy of the collection.
    That's an advantage on HTMLCollection because items could be modified during iteration and modification to elements inside the Array will still be a modification on original objects.

    Now we have two standard Arrays and can use concat() to join them and forEach to iterate the joined result.

提交回复
热议问题