Adding or removing a class from an HTML element with JavaScript
Published on 2020-05-23 • Modified on 2020-05-23
In this snippet, we will see how to add or remove a class from an HTML element with JavaScript. It can be done with the classList
property of the HTLM element we want to alter. In the following demo, we will remove or add the btn-primary
class from the button it contains it or not. In this case, we could also use the toggle
function.
/**
* I am using a JavaScript module to isolate the code of each snippet.
* In fact it's a Vue.js mixin. Take the code called by the mounted()
* or the snippetXX() function.
*/
export default {
methods: {
snippet92 () {
if (this.$refs.button92.classList.contains('btn-primary')) {
this.$refs.button92.classList.toggle('btn-primary')
} else {
this.$refs.button92.classList.add('btn-primary')
}
// or this.$refs.button92.classList.toggle('btn-primary')
}
}
}
HTML demo of the snippet
More on Stackoverflow Read the doc Random snippet