Home > Mobile >  Remove nested class from an element JavaScript
Remove nested class from an element JavaScript

Time:10-07

If I have some nested elements, how would I remove the class name of one that is nested deep with pure JavaScript?

For example:

<div class="wrapper">
 <div class="a">
  <div class="b">
   <div class="c">
    // Remove class name only of below element
    <div class="remove-me">Remove class name only of this element</div>
   </div>
  </div>
 </div>
</div>

I want to do this in pure JavaScript

CodePudding user response:

you can use elem.classList.remove("remove-me");.

example to select element:

let elem = document.querySelector('.wrapper>.a>.b>.c>.remove-me');

CodePudding user response:

Why can't you do it by directly getting and modifying this element? For example like this:

let element = document.getElementsByClassName('remove-me')[0];
console.log(element.classList); //here you can see this element classes
element.classList.remove('remove-me');
console.log(element.classList); //here you can see that we removed one
<div class="wrapper">
 <div class="a">
  <div class="b">
   <div class="c">
    // Remove class of below element
    <div class="remove-me">Remove class of this element</div>
   </div>
  </div>
 </div>
</div>

CodePudding user response:

Usually it's a better practice to select elements by an id.
But if all you have to go by is the class-name it can still be done fairly easily.
You can select the element using said class-name, and remove it with some built-in JS methods.

Selecting the element looks like this:

const element = document.querySelector('.remove-me');

Then removing the class-name can look like this,
which can be convinient if you have only a single class:

element.className = '';

Or like this if you have more:

element.classList.remove('remove-me');

CodePudding user response:

Your question might be duplicated but you can use below code

// Finding all elements of a class (creates an array of results)
let x = document.getElementsByClassName("remove-me");

// If it exists, remove it.
if(x.length > 0) { x[0].classList.remove("remove-me"); }
.remove-me {
  color : red
}
<div class="wrapper">
 <div class="a">
  <div class="b">
   <div class="c">
    <div class="remove-me">Remove class of this element</div>
   </div>
  </div>
 </div>
</div>

  • Related