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')
}
}
}
More on Stackoverflow Read the doc Random snippet
Call to action
Did you like this post? You can help me back in several ways: (use the "reply" link on the right to comment or to contact me )
- Report any error/typo.
- Report something that could be improved.
- Like and repost!
- Follow me on Bluesky 🦋
- Subscribe to the RSS feed.
- Click on the More on Stackoverflow buttons to make me win "Announcer" badges 🏅.
Thank you for reading! And see you soon on Strangebuzz! 😉
