How to Add/Remove a Class in JavaScript

How to add and remove classes in Javascript without jQuery

The following 3 functions work in browsers which don't support classList:

function hasClass(el, className)
{
if (el.classList)
return el.classList.contains(className);
return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'));
}

function addClass(el, className)
{
if (el.classList)
el.classList.add(className)
else if (!hasClass(el, className))
el.className += " " + className;
}

function removeClass(el, className)
{
if (el.classList)
el.classList.remove(className)
else if (hasClass(el, className))
{
var reg = new RegExp('(\\s|^)' + className + '(\\s|$)');
el.className = el.className.replace(reg, ' ');
}
}

https://jaketrent.com/post/addremove-classes-raw-javascript/

How to add/remove a class in JavaScript?

One way to play around with classes without frameworks/libraries would be using the property Element.className, which "gets and sets the value of the class attribute of the specified element." (from the MDN documentation).

As @matías-fidemraizer already mentioned in his answer, once you get the string of classes for your element you can use any methods associated with strings to modify it.

Here's an example:

Assuming you have a div with the ID "myDiv" and that you want to add to it the class "main__section" when the user clicks on it,

window.onload = init;

function init() {
document.getElementById("myDiv").onclick = addMyClass;
}

function addMyClass() {
var classString = this.className; // returns the string of all the classes for myDiv
var newClass = classString.concat(" main__section"); // Adds the class "main__section" to the string (notice the leading space)
this.className = newClass; // sets className to the new string
}

How to add and remove class from list items?

Here's a pure JavaScript way to do it (no dependencies). I prevented the default link behaviors for the sake of the demo.

const listItems = document.querySelectorAll('.sub_list_item');
function setActiveClass() { if (document.querySelector('.sub_list_item.active') != null) { document.querySelector('.sub_list_item.active').classList.remove('active'); } this.classList.add('active');}
listItems.forEach(item => { item.addEventListener('click', setActiveClass);});
// DEMO ONLY — REMOVEconst listLinks = document.querySelectorAll('.sub_list_link');listLinks.forEach(link => { link.addEventListener('click', e => e.preventDefault());});
.sub_list_item.active {  background-color: yellow;}
<ul class="side_menu" id="sideMenu">  <li class="list_header">    <p class="list_p">REVIEWS</p>    <ul class="sub_list">      <li class="sub_list_item" style="padding-top: 0px !important;">        <a href="https://www.facebook.com" target="_blank" class="sub_list_link">                    <i class="fas fa-layer-group padding_right"></i>                    All Reviews                  </a>      </li>      <li class="sub_list_item">        <a href="https://www.facebook.com" target="_blank" class="sub_list_link">                    <i class="fas fa-thumbs-up padding_right"></i>                    Best Albums                  </a>      </li>      <li class="sub_list_item">        <a href="https://www.facebook.com" target="_blank" class="sub_list_link">                    <i class="fas fa-thumbs-down padding_right"></i>                    Worst Albums                  </a>      </li>    </ul>  </li>  <li class="list_header">    <p class="list_p">GENRES</p>    <ul class="sub_list">      <li class="sub_list_item">        <a href="https://www.facebook.com" target="_blank" class="sub_list_link">                    <i class="fas fa-music padding_right"></i>                    Dub                  </a>      </li>      <li class="sub_list_item">        <a href="https://www.facebook.com" target="_blank" class="sub_list_link">                    <i class="fas fa-music padding_right"></i>                    Electronica                  </a>      </li>      <li class="sub_list_item">        <a href="https://www.facebook.com" target="_blank" class="sub_list_link">                    <i class="fas fa-music padding_right"></i>                    Grundge                  </a>      </li>    </ul>  </li></ul>

How can I add and remove an active class to an element in pure JavaScript

Use document.querySelectorAll to find the element which currently have the active class, then you can remove that class.

function myFunction(e) {
var elems = document.querySelectorAll(".active");
[].forEach.call(elems, function(el) {
el.classList.remove("active");
});
e.target.className = "active";
}

JSFIDDLE

Instead of document.querySelectorAll you can also use document.querySelector

 function myFunction(e) {
var elems = document.querySelector(".active");
if(elems !==null){
elems.classList.remove("active");
}
e.target.className = "active";
}

JSFIDDLE 2

Edit

Instead of iterating through the entire collection you can select the element which have a class active using document.queryselector. Also provide an id to the ul so that you can target the specific element

function myFunction(e) {  if (document.querySelector('#navList a.active') !== null) {    document.querySelector('#navList a.active').classList.remove('active');  }  e.target.className = "active";}
<style type="text/css">* {  margin: 0;  padding: 0;  box-sizing: border-box;}
header { width: 100%; height: auto; max-width: 600px; margin: 0 auto;}
nav { width: 100%; height: 40px; background-color: cornflowerblue;}
ul { list-style-type: none;}
li { display: inline-block;}
a { text-decoration: none; padding: 8px 15px; display: block; text-transform: capitalize; background-color: darkgray; color: #fff;}
a.active { background-color: cornflowerblue;}
<title>Navigation class Toggling</title>
<header> <nav> <ul onclick="myFunction(event)" id='navList'> <li><a href="#">home</a></li> <li><a href="#">about</a></li> <li><a href="#">service</a></li> <li><a href="#">profile</a></li> <li><a href="#">portfolio</a></li> <li><a href="#">contact</a></li> </ul> </nav></header>

Change (Add/Remove) CSS Class On Mobile With JS or jQuery

You could use $(window).width() < 700 and check if width < 700 then removeClass ten and addClass three.

This function will run even if you resize you window manually via mouse.

//Resize window
function resize() {
if ($(window).width() < 700) {
$('.myDiv').removeClass('ten').addClass('three');
}
}

Runable Example:

//Resize window
function resize() {
if ($(window).width() < 700) {
$('.myDiv').removeClass('ten').addClass('three');
}
}

//watch window resize
$(window).on('resize', function() {
resize()
});
.ten {
background: green;
}

.three {
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ui ten column grid myDiv">My Div</div>

Add or Remove class automatically in HTML

You just need to remove the "active" class from any <li> element that already has it set. Otherwise you end up with the "active" class on multiple elements. Here is one way to do that:

let getList=document.querySelectorAll("li")

getList.forEach(li=>{

li.addEventListener("click", function(){

// remove class from any currently active elements
getList.forEach(li => { li.classList.remove("active"); });

// then add the active class to the selected element
li.classList.add("active")

})
})
.list-item{
height:80px;
width:70px;
background-color:black
}

.list-item li{
color:white
}
.active{
border:5px soild blue;
list-style:none;
color:orange;

}
<body>
<ul class="list-item">

<li>Apple</li>
<li>Banana</li>
<li>Orange</li>

</ul>

</body>

Add or remove a class based on a condition

There’s a toggle method on .classList which takes a second argument (force).
This boolean argument essentially takes a condition that adds the class if true, and removes the class if false.

myEl.classList.toggle("myClass", myConditionIsMet);

Use vanilla javascript to add / remove class to a different element after clicking on another one

document.addEventListener("DOMContentLoaded", function() {
var faqContainers = document.getElementsByClassName('faq-container');
var faqToggle = document.getElementsByTagName('body')[0];
for (var i = 0; i < faqContainers.length; i++) {

faqContainers[i].addEventListener('click', function() {

if (faqToggle.classList.contains('faq-display')) {
faqToggle.classList.remove('faq-display');
// alert("remove faq display!");
} else {
faqToggle.classList.add('faq-display');
// alert("add faq display!");
}

});
}

});


Related Topics



Leave a reply



Submit