Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

332
Visualizações
Javascript Change the parent text color via button child

I want to append a button to any divs with the class name "colors". When the button is clicked the Parent's (of the clicked button) text color will change to the desired color. It only changes the last element.

Here's what I have so far. https://codepen.io/i-empty/pen/mdpLNEB

var colors = document.querySelectorAll('.colors');

for (var i = 0; i < colors.length; i++) {
 var btn = document.createElement('button'); 
  btn.classList.add('button');
  btn.textContent = "Change";

  colors[i].append(btn);
  
}
  btn.addEventListener("click", ChangeColor);

// Change Colors
function ChangeColor() {
  for (var _ = 0; _ < colors.length; _++) {
    colors[_].style.color = "red";
  }
}
.button {
    background-color: red;
  color: white;
  padding: 5px 10px;
  border-radius: 5px;
  bottom: 10px;
  float: right; 
  &:hover {
    cursor: pointer;
  }
  &:active {
    background-color: black;
    color: white;
  }
}
.colors {
  padding: 10px;
  border: 1px solid black;
  border-radius: 5px;
  width: 35%;
  margin: 10px 0;
  font-size: 20px;
  font-weight: bold;
  font-family: Sans-serif;
 
}
  <div class="colors">Hi</div>
  <div class="colors">Hello</div>
  <div class="colors">Goodbye</div>

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

I made some minor changes not really required but the most important one was adding the event handler, to the newly created button element, inside the loop and not only once at the end. That's why only your last button was triggering the event changing the colors.

Here's my solution:

let colors;

//init the gui once the document was loaded
document.addEventListener("DOMContentLoaded", function() {
  colors = document.querySelectorAll('.colors');
  init();
});

//Init the gui
function init(){ 
  //loop through the .colors divs
  for (let i = 0; i < colors.length; i++) {
    //add a new button to the current div
    let btn = document.createElement('button'); 
    btn.classList.add('button');
    btn.textContent = "Change";
    btn.addEventListener("click", ChangeColor);
    colors[i].append(btn);
  }
}

//Change text color to all .colors divs
function ChangeColor(event) {
  color = event.target.parentNode;
  if (color.style.color == "red")
      color.style.color = "black";
  else
      color.style.color = "red";
}
.button {
  background-color: red;
  color: white;
  padding: 5px 10px;
  border-radius: 5px;
  bottom: 10px;
  float: right; 
 }
 
&:hover {
  cursor: pointer;
}

&:active {
  background-color: black;
  color: white;
}

.colors {
  padding: 10px;
  border: 1px solid black;
  border-radius: 5px;
  width: 35%;
  margin: 10px 0;
  font-size: 20px;
  font-weight: bold;
  font-family: Sans-serif;
 
}
<div class="colors">Hi</div>
<div class="colors">Hello</div>
<div class="colors">Goodbye</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

Pick up your buttons. Add event listeners to all of them, and then when the function is called find the element's parent node and add a new class to it.

const colors = document.querySelectorAll('.colors');

for (var i = 0; i < colors.length; i++) {
  var btn = document.createElement('button');
  btn.classList.add('button');
  btn.textContent = "Change";
  colors[i].append(btn);
}

const buttons = document.querySelectorAll('button');

buttons.forEach(button => {
  button.addEventListener('click', changeColor, false);
});

// Change Colors
function changeColor() {
  this.parentNode.classList.add('red');
}
.button{background-color:red;color:#fff;padding:5px 10px;border-radius:5px;bottom:10px;float:right}
.colors{padding:10px;border:1px solid #000;border-radius:5px;width:55%;margin:10px 0;font-size:20px;font-weight:700;font-family:Sans-serif}
.red{color:red}
<div class="colors">Hi</div>
<div class="colors">Hello</div>
<div class="colors">Goodbye</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

var colors = document.querySelectorAll('.colors');

const ChangeColor = event => {
    if (event.target.parentNode.style.color === "red") {
    
event.target.parentNode.style.color = "black"
    } else {
event.target.parentNode.style.color =  "red"
    }
}

for (var i = 0; i < colors.length; i++) {
 var btn = document.createElement('button'); 
  btn.classList.add('button');
  btn.textContent = "Change";

  colors[i].append(btn);
  
  btn.addEventListener("click", ChangeColor);
}
.button {
    background-color: red;
  color: white;
  padding: 5px 10px;
  border-radius: 5px;
  bottom: 10px;
  float: right; 
  &:hover {
    cursor: pointer;
  }
  &:active {
    background-color: black;
    color: white;
  }
}
.colors {
  padding: 10px;
  border: 1px solid black;
  border-radius: 5px;
  width: 35%;
  margin: 10px 0;
  font-size: 20px;
  font-weight: bold;
  font-family: Sans-serif;
 
}
  <div class="colors">Hi</div>
  <div class="colors">Hello</div>
  <div class="colors">Goodbye</div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda