Reputation: 665
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?
Upvotes: 0
Views: 443
Reputation: 3604
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>
Upvotes: 0
Reputation: 51
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";
}
Upvotes: 0
Reputation: 395
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>
Upvotes: 2