select elements with same id in javascript

In HTML, each element should have a unique id. However, if you have multiple elements with the same id, you can select them using JavaScript in the following ways:

  1. Using getElementById method: You can use the getElementById method to select the first element with the given id. If there are multiple elements with the same id, this method will only return the first one.
index.tsx
const element = document.getElementById('your-id');
52 chars
2 lines
  1. Using querySelectorAll method: You can use the querySelectorAll method to select all elements that match a specified CSS selector, including elements with the same id. This method returns a NodeList, which you can loop through using the forEach method, for example.
index.tsx
const elements = document.querySelectorAll('#your-id');
elements.forEach(element => {
  // your code here
});
110 chars
5 lines

Note that it is generally bad practice to have multiple elements with the same id, and you should instead use classes or other attributes to group elements together.

gistlibby LogSnag