How to remove a class from elements in pure JavaScript?
var elems = document.querySelectorAll(".widget.hover");
[].forEach.call(elems, function(el) {
el.classList.remove("hover");
});
You can patch .classList
into IE9. Otherwise, you'll need to modify the .className
.
var elems = document.querySelectorAll(".widget.hover");
[].forEach.call(elems, function(el) {
el.className = el.className.replace(/\bhover\b/, "");
});
The .forEach()
also needs a patch for IE8, but that's pretty common anyway.
Remove specific class from group of elements without jquery
Remove .
from the classname
el.classList.remove("activeLang");
window.onload = function() {
var x = document.getElementsByClassName("activeLang"); console.log(x[0]); //will print the object [].forEach.call(x, function(el) { el.classList.remove("activeLang"); }); console.log(x[0]); //will no longer print the object};
<div class="header_content_lang"> <span class="langNav"> ... </span> <span class="langNav"> ... </span> <span class="langNav activeLang"> ... </span></div>
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>
Remove All Elements with the Same Class in Pure JavaScript
You have for(var i = 0; 1 < messages.length; i++)
but the 1
should be your variable named i
instead. like this: for(var i = 0; i < messages.length; i++)
Right now your code reads "keep looping if the number 1 is less than the number of messages"
var messages = document.querySelectorAll('.message');for(var i = 0; i < messages.length; i++){ messages[i].parentNode.removeChild(messages[i]);}
<div class="row"> <div class="column is-6--tablet"> <h2>Personal Information</h2> <div class="row"> <div class="column is-3"> <span class="message">Please enter your first name.</span> <label for="xFIRST_NAME">First Name</label> </div> <div class="column is-9"> <input type="text" name="xFIRST_NAME" value="<?php echo $xFIRST_NAME; ?>" required> </div> </div> <div class="row"> <div class="column is-3"> <span class="message">Please enter your last name.</span> <label for="xLAST_NAME">Last Name</label> </div> <div class="column is-9"> <input type="text" name="xLAST_NAME" value="<?php echo $xLAST_NAME; ?>" required> </div> </div> <div class="row"> <div class="column is-3"> <span class="message">Please enter your phone.</span> <label for="XPHONE">Phone</label> </div> <div class="column is-9"> <input type="tel" name="xPHONE" value="<?php echo $xPHONE; ?>" required> </div> </div> <div class="row"> <div class="column is-3"> <label for="xEMAIL">Email</label> </div> <div class="column is-9"> <input type="email" name="xEMAIL" value="<?php echo $xEMAIL; ?>" required> </div> </div> <div class="row patient-type"> <div class="column is-12"> <hr> <input type="radio" name="xPATIENT_STATUS" id="NEW_PATIENT" value="New Patient" <?php echo ($xPATIENT_STATUS === 'New Patient' ? 'checked' : ''); ?> required> <label for="NEW_PATIENT"> New Patient</label> <input type="radio" name="xPATIENT_STATUS" id="EXISTING_PATIENT" value="Existing Patient" <?php echo ($xPATIENT_STATUS === 'Existing Patient' ? 'checked' : ''); ?>> <label for="EXISTING_PATIENT"> Existing Patient</label> </div> </div> </div></div>
How to remove one class from many elements in javascript
Just target the elements with the active
class and remove the class from the classList
of each element.
const button = document.querySelector('button');
button.addEventListener('click', handleClick, false);
function handleClick() {
const active = document.querySelectorAll('.active');
active.forEach(el => el.classList.remove('active'));
}
.active { color: red; font-weight: bold; }
<button>Remove active class</button>
<div id="p1Highlight">
<div class="P1" id="m0">0</div>
<div class="P1" id="m1">1</div>
<div class="P1 active" id="m2">2</div>
<div class="P1" id="m3">3</div>
<div class="P1 active" id="m4">4</div>
<div class="P1" id="m5">5</div>
</div>
<div id="p2Highlight">
<div class="P2 active" id="a1">1</div>
<div class="P2" id="a2">2</div>
<div class="P2" id="a3">3</div>
<div class="P2" id="a4">4</div>
<div class="P2 active" id="a5">5</div>
</div>
Add/Remove class when clicking on element with pure JavaScript
Basically you are looping within your loop twice. I have fixed that.
You simply need to remove the previous active class and add new one like this:
document.querySelector(".sidenav a.active-list").classList.remove("active-list");
e.target.classList.add('active-list');
You can this: codepen:link https://codepen.io/emmeiWhite/pen/jOMZRxd
let elements = document.querySelectorAll('div, ul, li, a');
elements.forEach(i => {
i.addEventListener('click', function(e) {
document.querySelector(".sidenav a.active-list").classList.remove("active-list");
e.target.classList.add('active-list');
});
});
.sidenav {
width: 130px;
position: fixed;
z-index: 1;
top: 20px;
left: 10px;
overflow-x: hidden;
}
.sidenav ul {
background-color: black;
list-style: none;
padding: 0px;
padding-right: 0px;
}
.sidenav > ul > li {
color: white;
margin: 0px;
}
.sidenav a {
text-decoration: none;
font-size: 18px;
display: block;
line-height: 4em;
color: white;
background-color: black;
}
.sidenav a:hover {
color: grey;
}
.sidenav .active-list {
background-color: #e2c9be;
color: black;
}
<div id="active-buttons" class="sidenav" style="padding-top: 100px;">
<ul class="text-center">
<li>
<a href="#Profile" class="active-list">Profile</a>
</li>
<li>
<a href="#Experience">Experience</a>
</li>
<li>
<a href="#Projects">Projects</a>
</li>
<li>
<a href="#Skills">Skills</a>
</li>
</ul>
</div>
Vanilla JS remove a specific class from all elements that hold it
classList.toggle()
return a boolean valueclassList.toggle(class, force )
use a boolean force.querySelectorAll()
have aforEach()
a methodforEach()
method may have 3 arguments, the last one reffer to the used array
- you don't need to have ids for your elements...
- as you are using an arrow function in your event listener, you also don't need to use
e.currentTarget
to referel
also, in your code:document.getElementById(e.currentTarget.id)
or e.currentTarget
or el
are exactly the same DOM element
code:
document.querySelectorAll('.accordion-button').forEach((el,i,arr) =>
{
el.addEventListener('click', () =>
{
if (el.classList.toggle('no-rounded-bottom')) // flip class, then return (class added)?true:false
arr.forEach( elArr => // arr = querySelectorAll('.accordion-button')
elArr.classList.toggle('no-rounded-bottom', el === elArr ) // add or remove
) // class according to force test
})
})
document.querySelectorAll('.accordion-button').forEach((el,i,arr) =>
{
el.addEventListener('click', () =>
{
if (el.classList.toggle('no-rounded-bottom'))
arr.forEach( elArr =>
elArr.classList.toggle('no-rounded-bottom', el === elArr )
)
})
})
:root {
--bg-head-acc-root: #00667c;
--bg-body-acc-root: #004d5d;
}
textarea:hover,
input:hover,
textarea:active,
input:active,
textarea:focus,
input:focus,
label:focus,
button:focus,
button:active,
button:hover,
.btn:active,
.btn.active {
outline : 0px !important;
-webkit-appearance : none;
box-shadow : none !important;
}
div#accordionElements div.accordion-item {
background-color : var(--bg-body-acc-root);
border-radius : 10px;
}
div#accordionElements button.accordion-button {
background-color : var(--bg-head-acc-root);
color : #f5f5f5;
text-shadow : 1px 1px #000;
border-radius : 10px;
}
.accordion-button:after {
filter : brightness(0) invert(1);
}
ul.ListaMultiplaBorder {
padding : 0 15px;
border-top : 1px solid #044533;
box-shadow : inset 0 1px 0 #00667c;
}
.text-label-schede {
text-shadow : 0 1px 1px #000;
color : #5f9daa;
font-weight : normal;
}
.no-rounded-bottom {
border-bottom-left-radius : 0 !important;
border-bottom-right-radius : 0 !important;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" >
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<div class="accordion" id="accordionElements">
<div class="accordion-item border-0 my-4">
<h2 class="accordion-header" id="heading21">
<button id="mr-21"
class="accordion-button py-2 collapsed"
dir="rtl"
type="button"
data-bs-toggle="collapse"
data-bs-target="#r-21"
aria-expanded="false"
aria-controls="r-21">
<div class="row w-100">
<div class="col-2 recordstatus">
<p class="m-0 text-end">
<img src="/assets/images/ico_accesso_si.png" alt="Sample Image" title="Attivo">
</p>
</div>
<div class="col-10">
<h3 class="m-0 ms-3 py-2 fs-5">AAAA</h3>
</div>
</div>
</button>
</h2>
<div id="r-21"
class="accordion-collapse collapse"
aria-labelledby="heading21"
data-bs-parent="#accordionElements" style="">
<div class="accordion-body px-0 pt-0">
<p class="text-white p-3">Text</p>
</div>
</div>
</div>
<div class="accordion-item border-0 my-4">
<h2 class="accordion-header" id="heading22">
<button id="mr-22"
class="accordion-button py-2 collapsed"
dir="rtl"
type="button"
data-bs-toggle="collapse"
data-bs-target="#r-22"
aria-expanded="false"
aria-controls="r-22">
<div class="row w-100">
<div class="col-2 recordstatus">
<p class="m-0 text-end">
<img src="/assets/images/ico_accesso_si.png" alt="Sample Image" title="Attivo">
</p>
</div>
<div class="col-10">
<h3 class="m-0 ms-3 py-2 fs-5">BBBBB</h3>
</div>
</div>
</button>
</h2>
<div id="r-22" class="accordion-collapse collapse" aria-labelledby="heading22" data-bs-parent="#accordionElements">
<div class="accordion-body px-0 pt-0">
<p class="text-white p-3">Text</p>
</div>
</div>
</div>
</div>
Add/Remove class on click in pure JS
You need to use querySelectorAll()
to select more than one element, and then update the class on all of them. This can be done with .forEach()
to loop over them.
Similarly, use querySelectorAll()
to add the onclick
handler to each of the buttons.
document.querySelectorAll('.completeBtn').forEach(el => el.onclick = function(e) {
e.preventDefault();
let row = this.closest("tr");
row.querySelectorAll('.appOrd').forEach(el => el.classList.add('crossOut'));
row.querySelector('.resumeBtn').classList.remove('disabled');
this.classList.add('disabled');
});
document.querySelectorAll('.resumeBtn').forEach(el => el.onclick = function(e) {
e.preventDefault();
let row = this.closest("tr");
row.querySelectorAll('.appOrd').forEach(el => el.classList.remove('crossOut'));
row.querySelector('.completeBtn').classList.remove('disabled');
this.classList.add('disabled');
});
.crossOut {
text-decoration: line-through;
}
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" />
<table class="table table-bordered">
<thead>
<tr class="text-center">
<th scope="col">Name</th>
<th scope="col">Phone number</th>
<th scope="col">Application time</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody>
<tr class="text-center">
<td scope="row" class="appOrd">Name</td>
<td class="appOrd">Phone number</td>
<td class="appOrd">2021-02-07 08:40:48</td>
<td>
<a class="btn btn-success resumeBtn disabled" href="#">Resume</a>
<a class="btn btn-danger completeBtn" href="#">Complete</a>
</td>
</tr>
<tr class="text-center">
<td scope="row" class="appOrd">Name 2</td>
<td class="appOrd">Phone number 2</td>
<td class="appOrd">2021-02-06 09:00:50</td>
<td>
<a class="btn btn-success resumeBtn disabled" href="#">Resume</a>
<a class="btn btn-danger completeBtn" href="#">Complete</a>
</td>
</tr>
</tbody>
</table>
Related Topics
Is There a JavaScript Strcmp()
Stop Cursor from Jumping to End of Input Field in JavaScript Replace
JavaScript to Check When the Browser Window Is Closed
Jqgrid Gridunload/ Griddestroy
How to Get the Index of an Array in a Meteor Template Each Loop
Find All Text Nodes in HTML Page
How to Set a Cookie with Expire Time
Jquery Attribute Selector Variable
Differencebetween Document and Document in JavaScript
Difference Between Dot Notation and Bracket Notation in JavaScript
Is Performing a Mapping Operation Without Using Returned Value an Antipattern
JavaScript Getelementbyid Based on a Partial String
How to Get Index in Handlebars Each Helper
How to Register Event with Useeffect Hooks