HTML - The class attribute manipulation in the DOM.
The DOM Web API has a special function to select on class: the getElementsByClassName() function
You can select the class with a selector
// the first one
document.querySelector(".myclass");
// All
document.querySelectorAll(".myclass");
$('.myclass')
How to select an element that contains two class values.
<p class="first">Paragraph with one class value</p>
<p class="first second">The Paragraph with two class values should be in red</p>
let element = document.querySelector(".first.second");
element.style.setProperty('color', 'red');
<div class="foo bar"></div>
element = document.querySelector(".bar");
console.log("Is the class foo present ? "+ element.classList.contains("foo"));
toggle (or toggling) means to:
The en-US/docs/Web/API/DOMTokenList/toggle:
element.classList.toggle("className")
// The same as
if (element.classList.contains("className")){
element.classList.remove("className");
} else {
element.classList.add("className");
}
A demo with Native Javascript
.toggle {
color:blue;
}
<button class="toggle" src="#">Toggled</button>
document.querySelectorAll("button").forEach(element => {
element.addEventListener("click", function () {
result = element.classList.toggle("toggle");
if (result){
element.innerText = "Toggled";
} else {
element.innerText = "UnToggled";
}
});
});
If you use Jquery, you can use the JQuery Toggle function
document.getElementById(Id).classList.add('is-shown','is-blue')
document.querySelector('.js-nav').classList.add('is-shown')
document.querySelector('.js-nav').classList.add('is-shown is-blue'.split(' '))
event.target.classList.add('is-selected')
With the addClass Jquery Method
.beauty-blue { color: blueviolet; }
$( "p" ).addClass( "beauty-blue" )
<p>The text should be blue violet because the class 'beauty-blue' was added at runtime</p>
You can control it by looking the DOM element with the devtool.
Example: with chrome:
document.getElementById(Id).classList.remove('is-shown')
With the removeClass Jquery Method
$( "p" ).removeClass( "beauty-blue" )
<p class="beauty-blue">The text should be black because the class 'beauty-blue' was removed</p>
.beauty-blue { color: blueviolet; }
You can control it by looking the DOM element with the devtool.
Example: with chrome: