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

468
Visualizações
How to change the color of the certain element when there are multiple element with the same class?

I have HTML structure like:

<a class="parent-element">
 <h2 class="link1">link</h2>
</a>

<a class="parent-element">
 <h2 class="link2">link</h2>
</a>

<a class="parent-element">
 <h2 class="link3">link</a>
</a>

I want to add the class to the parent element for clicked link, and for instance, I click on the "link1" then change the background of his parent then when I click on the "link2" add the class to "link2" and remove from "link1"

I was trying with:

     $(".parent-element").addClass("myClass");

But, it's far from what I want to get :)

Thanks in advance!

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

0

Use this keyword for adding class to the current element.

$(".parent-element").click(function() {
  $(".parent-element").removeClass("active");
  $(this).addClass("active");
})
.active{
   color: hotpink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<a class="parent-element">
  <h2 class="link1">link</h2>
</a>

<a class="parent-element">
  <h2 class="link2">link</h2>
</a>

<a class="parent-element">
  <h2 class="link3">link</h2>
</a>

about 4 years ago · Juan Pablo Isaza Relatório

0

you can try this -

$(".parent-element").click(function() {
  $(".parent-element").removeClass("myClass");
  $(this).addClass("myClass");
})
.myClass {
  color: red;
}
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<a class="parent-element">
  <h2 class="link1">link</h2>
</a>
<a class="parent-element">
  <h2 class="link2">link</h2>
</a>
<a class="parent-element">
  <h2 class="link3">link
</a>

about 4 years ago · Juan Pablo Isaza Relatório

0

you can target the parent with event.target.parentNode.classList.add("clicked") but with your current code, you don't need to target the parent or use js to change the color. Because tag is the clickable element(not h2) and when you click on it, browser knows the event, target element etc.. You can simply create a css class like

a.parent-element:visited {
  color: green;
}

so, you dont even need js for it

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