[Solved] How trigger an event individually to different instances of the same id [duplicate]


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

solved How trigger an event individually to different instances of the same id [duplicate]