Marie
Marie

Reputation: 163

Add and remove classes in javascript without jquery

i have some paragraphs. At first one of that should have red color and after click it should become black, and clicked one should become red. I need to change red each paragraph when it is clicked and remove the class when another one is clicked. I should do it with javascript

var p = document.querySelectorAll("p");
for( var i = 0; i < p.length; i++ ){
	p[i].addEventListener("click", makeRed);
	p[0].classList.add("active");
}

function makeRed(){
	p[0].classList.remove("active");

	if( this.classList.contains("active")){
		this.classList.remove("active");
    } else{
    	this.classList.add("active");
    }
    
}
 .active{
    color: red;
  }
<p>Text First</p>
<p>Text Second</p>
<p>Text Third</p>

Upvotes: 2

Views: 1033

Answers (3)

Farhan Tahir
Farhan Tahir

Reputation: 2144

Simply use document.querySelectorAll to get all elements and reset their class by removing active and then simply add class to current element.

var p = document.querySelectorAll("p");
for( var i = 0; i < p.length; i++ ){
	p[i].addEventListener("click", makeRed);
	p[0].classList.add("active");
}

function makeRed(){    	
    [...document.querySelectorAll('p')]
      .map(elem => elem.classList.remove("active"));
    this.classList.add("active");        
}
 .active{
    color: red;
  }
<p>Text First</p>
<p>Text Second</p>
<p>Text Third</p>

Upvotes: 0

Your code is good, just have a little logical problem :)

var p = document.querySelectorAll("p");
for( var i = 0; i < p.length; i++ ){
	p[i].addEventListener("click", makeRed);
	p[0].classList.add("active");
}

function makeRed(){
	if( this.classList.contains("active")){
		this.classList.remove("active");
    } else{
        for( var i = 0; i < p.length; i++ ){
            p[i].classList.remove("active");
        } 
    	this.classList.add("active");
    }
    
}
 .active{
    color: red;
  }
<p class="active">Text First</p>
<p>Text Second</p>
<p>Text Third</p>

Upvotes: 2

Priyal Pithadiya
Priyal Pithadiya

Reputation: 889

Try with below solution,

var p = document.querySelectorAll("p");
for( var i = 0; i < p.length; i++ ){
   
	p[i].addEventListener("click", makeRed);
	p[0].classList.add("active");
}

function makeRed(){
   var elems = document.querySelectorAll(".active");
    [].forEach.call(elems, function(el) {
      el.classList.remove("active");
    });
	if( this.classList.contains("active")){
		this.classList.remove("active");
    } else{
    	this.classList.add("active");
    }
    
}
.active{
    color: red;
  }
<p>Text First</p>
<p>Text Second</p>
<p>Text Third</p>

Upvotes: 0

Related Questions