0

So I have a few elements:
HTML:

<button class="btn-post">Post</button>
<button class="btn-post">Post</button>
<button class="btn-post">Post</button>
<button class="btn-post">Post</button>

As you can see, these buttons have the class btn-post and when someone clicks a button and activates an event.

I want to replace all the btn-post classes with btn btn-success (btn and btn-success)
Any helpful advice?

Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32
Capt 171
  • 665
  • 5
  • 15
  • Loop through elements selected with `querySelectorAll`. https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll – evolutionxbox Jan 15 '21 at 11:52

3 Answers3

2

Try something like this

const btns = document.querySelectorAll(".btn-post")

btns.forEach(btn => {
  btn.onclick = () => btns.forEach(_btn => _btn.className = "btn btn-success")
})
.btn-post {
  background-color: black;
  color: white;
}

.btn-success {
  background-color: green;
}
<button class="btn-post">Post</button>
<button class="btn-post">Post</button>
<button class="btn-post">Post</button>
<button class="btn-post">Post</button>
ptothep
  • 415
  • 3
  • 10
0

You can use javascript to do so.

var elems = document.getElementsByClassName("btn-post");

for(var i = 0; i < elems.length; i++) {
    elems[i].className = "btn btn-success";
}
  • 1
    This won't work. See [What do querySelectorAll and getElementsBy* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) – charlietfl Jan 15 '21 at 11:54
0

You can get all the elements with class bln-post, and create an array from it. You can then edit the class names using classList API.

const elems = document.getElementsByClassName('btn-post')

Array.from(elems).forEach(el => {
  el.classList.remove('btn-post');
  el.classList.add('btn');
  el.classList.add('btn-success');
})
.btn-success {
  color: green
}
<button class="btn-post">Post</button>
<button class="btn-post">Post</button>
<button class="btn-post">Post</button>
<button class="btn-post">Post</button>
Pushkin
  • 3,336
  • 1
  • 17
  • 30