EN
JavaScript - add or remove single class name from element
6
points
In this short article we would like to show how to add or remove single class name using JavaScript.
Quick solution:
var element = document.querySelector('#element');
element.classList.remove('class-name-to-remove');
element.classList.add('class-name-to-add');
// before add / remove:
// <div class="navbar class-name-to-remove"></div>
// after add / remove:
// <div class="navbar class-name-to-add"></div>
Practical example:
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
.background {background: silver}
.border {border: 5px solid orange}
.normal-font {font-size: 13px}
.big-font {font-size: 30px}
</style>
</head>
<body>
<div id="element" class="background big-font">Some text here...</div>
<script>
var element = document.querySelector('#element');
element.classList.remove('big-font');
element.classList.add('border');
element.classList.add('normal-font');
</script>
</body>
</html>
Add / remove border on click action example
As alternative we are able to modify element classes on used demand.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
.background {background: silver}
.border {border: 5px solid orange}
</style>
</head>
<body>
<div id="element" class="background big-font">Some text here...</div>
<button onclick="addBorder()">Add border</button>
<button onclick="removeBorder()">Remove border</button>
<script>
var element = document.querySelector('#element');
function addBorder() {
element.classList.add('border');
}
function removeBorder() {
element.classList.remove('border');
}
</script>
</body>
</html>