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

118
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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