2

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>

1
  • 1
    @Grégory NEUT non) je ne veux pas ecrire comme ca, merci! Commented Jun 20, 2018 at 8:03

3 Answers 3

2

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.