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

70
Visualizações
Changing specific element with the same function

So I want to code a Vanilla Script which changes the style of a text individually. Heres the code of it:

<body>
<p class="black_to_red" onclick="get_red()">If I click this, I am red</p>
<p class="black_to_red" onclick="get_red()">If I click this, I am red</p>
<script>
function get_red() {
    text = document.getElementsByClassName("black_to_red");
    for (let i = 0; i < text.length; i++) {
        text[i].style.color = 'red';
    }
}
</script>
</body>

But this code only works kinda. The reason why I say "kinda" is because when I click on a text it changes the style of both textes. Is there a way to make it only effect the specific text I click on it?

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

0

There are several ways to do that.

If you stick with onclick attributes, then pass this as argument, so the function knows which element got the click event.

function get_red(elem) {
    elem.style.color = 'red';
}
<p class="black_to_red" onclick="get_red(this)">If I click this, I am red</p>
<p class="black_to_red" onclick="get_red(this)">If I click this, I am red</p>

Better practice is to bind the click event handler using code, and not use onclick attributes. In that case this will refer to the element that got the click event:

function get_red() {
    this.style.color = 'red';
}
document.querySelectorAll(".black_to_red").forEach(function (elem) {
    elem.addEventListener("click", get_red);
});
<p class="black_to_red">If I click this, I am red</p>
<p class="black_to_red">If I click this, I am red</p>

about 4 years ago · Juan Pablo Isaza Relatório

0

Passing the current DOM element has parameter will do what you want.

Change you HTML to

<p class="black_to_red" onclick="get_red(this)">If I click this, I am red</p>

And the function to

function get_red(element) {
    element.style.color = 'red';
}

Obs: It is always preferable to use listeners instead of onclick

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