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

141
Vistas
Changing class without variables in javascript

I have attached 2 of my divs below. When the icon inside heart is clicked, if the class name is far then it should change from far to fas. But if the class name has been changed to fas, it should change back to far. I'm not sure how to do this becuase I have many divs.

<div class="cont">
     <h2>A header</h2>
     <div class="heart">
          <i onclick="like(example)"  class="fas fa-heart"></i>
     </div>
</div>
<div class="cont">
     <h2>A header#2</h2>
     <div class="heart">
          <i onclick="like1()"  class="fas fa-heart"></i>
     </div>
</div>

This is the javascript I currently have.

function like(example){
     if(example.classList=="far fa-heart"){
         example.classList.toggle="fas fa-heart";
     } else{
         example.classList.toggle="far fa-heart";
    }
}

I want this to be in just 1 function without making a variable for all the tags in javascript. I'm still learning... Thanks for your help!

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

I can't find a good dupetarget for this. Basically, you can hook click on a parent element containing all of these (body if nothing else) and only take action if the click passed through the fa-heart element when bubbling:

theContainer.addEventListener("click", function(event) {
    // Did the click pass through an `.fa-heart` element?
    const heart = event.target.closest(".fa-heart");
    if (heart && this.contains(heart)) {
        // Yes, and that element is inside this container; toggle it
        heart.classList.toggle("far");
        heart.classList.toggle("fas");
    }
});

See closest, contains, and toggle for details.

Live Example:

const theContainer = document.body;
theContainer.addEventListener("click", function(event) {
    // Did the click pass through an `.fa-heart` element?
    const heart = event.target.closest(".fa-heart");
    if (heart && this.contains(heart)) {
        // Yes, and that element is inside this container; toggle it
        heart.classList.toggle("far");
        heart.classList.toggle("fas");
    }
});
.fa-heart {
    display: inline-block;
    width: 20px;
    color: white;
}
.fas {
    background-color: red;
}
.fas::after {
    content: 'fas';
}
.far {
    background-color: green;
}
.far::after {
    content: 'far';
}
<div class="cont">
     <h2>A header</h2>
     <div class="heart">
          <i class="fas fa-heart"></i>
     </div>
</div>
<div class="cont">
     <h2>A header#2</h2>
     <div class="heart">
          <i class="fas fa-heart"></i>
     </div>
</div>

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use a function that accepts an HTML element as a parameter and toggles the classes.

function like1(element) {  
  element.classList.toggle("fas");
  element.classList.toggle("far");
}
.fas {
  color: green;
}
.far {
color: red;
}
<div class="cont">
     <h2>A header</h2>
     <div class="heart">
          <i onclick="like1(this)"  class="fas fa-heart">Like</i>
     </div>
</div>
<div class="cont">
     <h2>A header#2</h2>
     <div class="heart">
          <i onclick="like1(this)"  class="fas fa-heart">Like</i>
     </div>
</div>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Edited the answer to add the HTML and import fontawesome, since my first answer was done on my phone.

function toggleHearts() {
  document.querySelectorAll(".heart")
    .forEach(elm => elm.addEventListener("click", (e) => {
      e.target.classList.toggle("far");
      e.target.classList.toggle("fas");
    }));
}

toggleHearts()
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css" integrity="sha512-YWzhKL2whUzgiheMoBFwW8CKV4qpHQAEuvilg9FAn5VJUDwKZZxkJNuGM4XkWuk94WCrrwslk8yWNGmY1EduTA==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>

<div class="container">
  <h2>A header</h2>
  <div class="heart">
    <i class="fas fa-heart"></i>
  </div>
</div>
<div class="container">
  <h2>A header#2</h2>
  <div class="heart">
    <i class="fas fa-heart"></i>
  </div>
</div>

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