Languages
[Edit]
EN

JavaScript - add or remove single class name from element

6 points
Created by:
Laylah-Walsh
624

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>
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join