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

117
Visualizações
HTML Javascript multiple like buttons on a single page

I have a social media style website, that I want to have a like-feature for the posts, It's supposed to be very simple for now.

With this code, only the first post's like button works, so how do I make them individual, without having to rewrite code a thousand times?

Javascript:

const getLike = document.querySelector('.like');
const getLikeNum = document.querySelector('.likeNum');

let like = 0;

increaseLike = () => {
like ++
getLikeNum.innerHTML = `${like}`
}
    
likeClick = () => {
increaseLike()
}
    
getLike.addEventListener(('click'), likeClick)

HTML:

<div id="opslag-gruppe">
          <div class="opslag">
            <div class="bar">
              <button class="like"><img src="hjerte.png" class="hjerte"></button>
              <p class="likeNum">0</p>
            </div>
          </div>

          <div class="opslag">
            <div class="bar">
              <button class="like"><img src="hjerte.png" class="hjerte"></button>
              <p class="likeNum">0</p>
            </div>
          </div>

          <div class="opslag">
            <div class="bar">
              <button class="like"><img src="hjerte.png" class="hjerte"></button>
              <p class="likeNum">0</p>

            </div>
          </div>

          <div class="opslag">
            <div class="bar">
              <button class="like"><img src="hjerte.png" class="hjerte"></button>
              <p class="likeNum">0</p>
            </div>
          </div>
        </div>

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

0

You have use querySelectorAll and then use forEach .

const likeButtons = [...document.querySelectorAll(".likeButton")];

let likeCount = 0;


function like () {
  likeCount++;
  console.log(likeCount);
}

likeButtons.forEach(item => {
  item.addEventListener("click", like);
});
<button class="likeButton">Like</button>
<button class="likeButton">Like</button>
<button class="likeButton">Like</button>
<button class="likeButton">Like</button>
<button class="likeButton">Like</button>
<button class="likeButton">Like</button>

about 4 years ago · Juan Pablo Isaza Relatório

0

  1. Use querySelectorAll to get all the elements with class like, and iterate over them.

  2. When you iterate over each button have your addEventListener return a function (a closure) that initialises the count, and maintains it only for that button. This way you don't need global variables.

// Set the intial like to 0
function likeClick(like = 0) {

  // Return a new function that is called when
  // the click on the button is called
  return function (e) {

    // Find the closest `bar` parent
    const bar = e.target.closest('.bar');

    // Grab the `p` element within that parents child elements
    const likeNum = bar.querySelector('p');

    // Update the like variable
    likeNum.textContent = ++like;
  }
}

// Cache the elements
const getLike = document.querySelectorAll('.like');

// For every element add a listener that
// calls the function that initialises the count and
// returns the function that *is* called when the
// button is clicked, and updates the count
getLike.forEach(like => like.addEventListener('click', likeClick(), false));
<div id="opslag-gruppe">
  <div class="opslag">
    <div class="bar">
      <button class="like"><img src="https://dummyimage.com/50x50/704a70/fff&text=Click" class="hjerte"></button>
      <p class="likeNum">0</p>
    </div>
  </div>
  <div class="opslag">
    <div class="bar">
      <button class="like"><img src="https://dummyimage.com/50x50/704a70/fff&text=Click" class="hjerte"></button>
      <p class="likeNum">0</p>
    </div>
  </div>
  <div class="opslag">
    <div class="bar">
      <button class="like"><img src="https://dummyimage.com/50x50/704a70/fff&text=Click" class="hjerte"></button>
      <p class="likeNum">0</p>
    </div>
  </div>
</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

If you use querySelectorAll to find ALL the buttons you can assign a simple event handler to each and simplify the whole process. That said the number of clicks really needs to be stored somewhere like a database otherwise it is ephemeral and lasts only as long as the pageview and is per-person. The problem with logging the number of clicks/likes in this example is that there is no unique identifiers assign to the individual items in the parent container ...

document.querySelectorAll('button.like').forEach(bttn=>{
  bttn.addEventListener('click',function(e){
    this.nextElementSibling.textContent=Number( this.nextElementSibling.textContent ) + 1;
  });
})
<div id="opslag-gruppe">

  <div class="opslag">
    <div class="bar">
      <button class="like"><img src="hjerte.png" class="hjerte"></button>
      <p class="likeNum">0</p>
    </div>
  </div>

  <div class="opslag">
    <div class="bar">
      <button class="like"><img src="hjerte.png" class="hjerte"></button>
      <p class="likeNum">0</p>
    </div>
  </div>

  <div class="opslag">
    <div class="bar">
      <button class="like"><img src="hjerte.png" class="hjerte"></button>
      <p class="likeNum">0</p>
    </div>
  </div>

  <div class="opslag">
    <div class="bar">
      <button class="like"><img src="hjerte.png" class="hjerte"></button>
      <p class="likeNum">0</p>
    </div>
  </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