简体   繁体   中英

How to make a JavaScript function run on all elements of the page

I want to add a class to the parent element that has buttons inside it.

I am running a JavaScript function but it only happens on the first element of the page. How can I prevent it from stopping on the first one, please?

 function createButtonWrapper () { var buttonList = document.querySelector('.article ul li [class^="ck-button"]'); var buttonWrapper = buttonList.parentNode.parentNode; if (buttonList){ buttonWrapper.classList.add('button-wrapper'); } } createButtonWrapper(); 
 section { display: flex; flex-direction: column; justify-content: flex-start; } a[class^="ck-button"] { padding: 20px; color: white; display: inline-block; } .ck-button-one { background: #00C853; } .ck-button-two { background: #00B8D4; } .ck-button-three { background: #DD2C00; } .ck-button-four { background: #311B92; } .button-wrapper { display: flex; justify-content: flex-start; flex-wrap: wrap; list-style: none; padding: 0; /*li{ margin: 0 0 0 $spacing*2; }*/ } 
 <section> <div class="article"> <ul> <li> <a class="ck-button-one">Button-1</a> <a class="ck-button-two">Button-2</a> <a class="ck-button-three">Button-3</a> <a class="ck-button-four">Button-4</a> </li> </ul> </div> <div class="article"> <ul> <li> <a class="ck-button-one">Button-1</a> <a class="ck-button-two">Button-2</a> <a class="ck-button-three">Button-3</a> <a class="ck-button-four">Button-4</a> </li> </ul> </div> </section> 

Use the forEach method like so:

buttonList.forEach(function(element) { 
  element.classList.add('button-wrapper');
});

So full code:

function createButtonWrapper () {
    var buttonList = document.querySelectorAll('.article ul li [class^="ck-button"]');

    if (buttonList){
        buttonList.forEach(function(element) { 
          element.classList.add('button-wrapper');
        });
    }
}
createButtonWrapper();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM