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

215
Vistas
How trigger an event individually to different instances of the same id

I have a list and I want to trigger an event individually with the same javascript code without define an id for each. For example, I want when I click each item the inner text changes to the color it says. In other words, I want the code knows where I'm clicking and apply the function to that particular item, and don't want to use id=color1", id=color2", id=color3". Any help appreciated!

<ul>
<li onclick="jsCode" id="color">Red<li>
<li onclick="jsCode" id="color">Blue<li>
<li onclick="jsCode" id="color">Green<li>
</ul>
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I think the easiest way to do this is to add a data attribute to each list item that references the colour, and then add that colour (defined in the CSS) to the the element's classList.

const list = document.querySelector('ul');
list.addEventListener('click', handleClick, false);

function handleClick(e) {
  if (e.target.matches('li')) {
    const { id } = e.target.dataset;
    e.target.classList.add(id);
  }
}
.red { color: red; }
.blue { color: blue; }
.green { color: green; }
li:hover { cursor: pointer; }
<ul>
  <li data-id="red">Red</li>
  <li data-id="blue">Blue</li>
  <li data-id="green">Green</li>
</ul>

Additional documentation

  • classList

  • matches

  • addEventListener

  • Destructuring assignment


Or if you don't want to use data attributes pick up the colour from the text content of each list item.

const list = document.querySelector('ul');
list.addEventListener('click', handleClick, false);

function handleClick(e) {
  if (e.target.matches('li')) {
    const { textContent } = e.target;
    const color = textContent.toLowerCase();
    e.target.classList.add(color);
  }
}
.red { color: red; }
.blue { color: blue; }
.green { color: green; }
li:hover { cursor: pointer; }
<ul>
  <li>Red</li>
  <li>Blue</li>
  <li>Green</li>
</ul>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Warning: Your problem here is that XHTML standards do not allow multiple elements with the same ID. This is simply not allows in XML, XHTML, or HTML 5. This is not just bad practice, but code which will most likely break in production as your application gets larger and less maintainable.


Solution 1: Use Classes

If you are using the same ID so that you can style the elements the same way, then you should be using classes:

<li class="color" id="red">Red</li>
<li class="color" id="blue">Blue</li>
<li class="color" id="green">Green</li>

Solution 2: Use querySelectorAll

Using document.getElementById will target only the first element with the specified ID (reference the warning above).

If you still insist on having multiple elements with the same ID, then there is one solution left (although proceed with caution).

document.querySelectorAll will accept a query selector (similar to CSS selectors) as a parameter and find all elements which match the provided query selector. So document.querySelectorAll('li') will return a NodeList (similar to an array) of <li /> elements. You can use the same function to grab all the elements with id="color":

const colors = Array.from(document.querySelectorAll('#color'));

colors.forEach(listItem => {
    const color = listItem.textContent.toUpperCase();

    listItem.addEventListener('click', () => {
        alert(`You clicked on ${color}`);
    });
});

You can checkout this codepen for a demo: https://codepen.io/virajshah21/pen/gOvvqEj

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