select multiple elements by id in javascript

You can select multiple elements by id in JavaScript by using the document.querySelectorAll() method and passing in a CSS selector that targets the ids of the elements you want to select. The method returns a NodeList object, which is similar to an array, containing all the matching elements.

Here's an example code snippet that selects two elements with ids "element1" and "element2":

index.tsx
const elements = document.querySelectorAll("#element1, #element2");

// loop through the NodeList to access each selected element
elements.forEach(element => {
  console.log(element);
});
188 chars
7 lines

In this example, the CSS selector #element1, #element2 targets elements with ids "element1" and "element2", which are passed as separate selectors separated by a comma. The NodeList returned by document.querySelectorAll() is then accessed using forEach() to log each selected element to the console.

Note that document.querySelectorAll() returns all matching elements, so it can potentially return multiple elements with the same id, which is not valid HTML. Therefore, it's best to use unique ids for each element on the page.

gistlibby LogSnag