Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

76
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda