Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

But, it’s far from what I want to get 🙂

Thanks in advance!

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading