如何使JavaScript函数在页面的所有元素上运行

时间:2018-10-04 10:31:40

标签: javascript function

我想向其内部具有按钮的父元素添加一个类。

我正在运行JavaScript函数,但是它仅在页面的第一个元素上发生。请问如何防止它在第一个停止?

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>

1 个答案:

答案 0 :(得分:2)

像这样使用forEach方法:

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

完整的代码:

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

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