Home > Mobile >  Remove class from all element on webpage
Remove class from all element on webpage

Time:11-03

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:

  1. Remove from all elements on my webpage this class: text-danger invalid
  2. add class to selected element
  3. show message Swal

I have problem with 1.

How can I repair it?

Please help me :)

CodePudding user response:

You have 2 issues with your code:

  1. There's an issue with your selector passed in line 2. As Ivan suggest below:
document.querySelectorAll("text-danger.invalid");
  1. 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

CodePudding user response:

You have a number of issues with your code:

  1. querySelectorAll() uses CSS selectors. So if you need to choose all elements with two classes, you need to use ".class-one.class-two".
  2. classList.remove() does not allow spaces, so separate classes with a comma.
  3. You can simplify your 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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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

  • Related