0

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>

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

1 Comment

It should be querySelectorAll() and not querySelector(), which select only the first element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.