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

148
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 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