I am beginner web developer. I have small problem with remove class from all elements on my webpage.
I have this code:
showErrorMessage(message, className) {
let elems = document.querySelectorAll("text-danger invalid");
[].forEach.call(elems, function(el) {
el.classList.remove("text-danger invalid");
});
document.querySelector(className).className += " text-danger invalid";
Swal.fire(
'Błąd',
message,
'error',
);
},
This code work fine, but not remove old class from div. I need:
I have problem with 1.
How can I repair it?
Please help me :)
You have 2 issues with your code:
document.querySelectorAll(".text-danger.invalid");
element.classList.remove() accepts classes as separate strings (see the MDN Docs). Replace line 4 with:el.classList.remove("text-danger", "invalid");
EDIT: Incorporated the suggestions from below comments
You have a number of issues with your code:
querySelectorAll() uses CSS selectors. So if you need to choose all elements with two classes, you need to use ".class-one.class-two".classList.remove() does not allow spaces, so separate classes with a comma.forEach().So here is the code that should work:
const elems = document.querySelectorAll(".text-danger.invalid")
elems.forEach((item) => {
item.classList.remove("text-danger", "invalid")
})
See also the code snippet
function remove() {
let elems = document.querySelectorAll(".text-danger.invalid")
elems.forEach((item) => {
item.classList.remove("text-danger", "invalid")
})
}
.text-danger.invalid {
color: red;
}
<div class="text-danger invalid">Text</div>
<div class="text-danger invalid">Text</div>
<button onclick="remove()">Remove classes</button>
querySelectorAll is array-like, is not array
Use Array.from for convert it to array
const elems = document.querySelectorAll("text-danger invalid");
Array.from(elems).forEach(e => {
e.classList.remove("text-danger", "invalid");
});
Notice: Separate classes in classList.remove