Vanilla JS - How to check if children contain color class, remove the actual class if it exists, then add new class?

55 views Asked by At

I'm using this code:

if ( selectColor.value == "R" & selectDiv.value == "grandParent" ) {
  grandParent.children[0].classList.add("red")
} 
if ( selectColor.value == "R" & selectDiv.value == "parent-1" & parent1.children[0].contains('red') == false) {
  parent1.children[0].classList.add("red")
}

The first if statement works fine. The second doesn't. What I'm trying to do is check if a div has a class or not, if not, add the selected color class,if it already has a class, remove it and add the new selected class.

I couldn't get to the answer of this exact logic myself using others posts. I'm learning with no live help for 4 months (until now) through internet courses, so bear with me if you can.

1

There are 1 answers

0
collab-with-tushar-raj On

Let's break your problem into sub-problems:-

Check if a div has a class or not

var root = document.querySelector('.root')
console.log(root.classList.contains('root')) // returns true
console.log(root.classList.contains('hello')) // returs false
<div class='root'></div>

Add the selected colour class

var myDiv = document.querySelector('#myDiv');
myDiv.classList.add('root');
console.log(myDiv);
<div id="myDiv"></div>

Check if it already has a class

var div = document.querySelector('.someClassName');
console.log(div.classList.contains('someClassName'));
<div class="someClassName"></div>

Remove the existing class

var myDiv = document.querySelector('.specialClass');
console.log(myDiv); // myDiv before removal
myDiv.classList.remove('specialClass');
console.log(myDiv); //myDiv after removal
<div class="specialClass"></div>

To combine all of the above scenarios in your problem statement, which is, What I'm trying to do is check if a div has a class or not, if not, add the selected color class,if it already has a class, remove it and add the new selected class.

var div1 = document.querySelector('.class_div1');
if(div1.classList.contains('class_div1')){
  div1.classList.remove('class_div1');
  div1.classList.add('new_selected_class');
} else {
  div1.classList.add('selected_color_class');
}

console.log(div1)
<div class="class_div1"></div>