Home  >  Article  >  Web Front-end  >  How to Work with Multiple Elements with the Same ID in JavaScript?

How to Work with Multiple Elements with the Same ID in JavaScript?

DDD
DDDOriginal
2024-11-19 12:00:04281browse

How to Work with Multiple Elements with the Same ID in JavaScript?

Working with Multiple Elements with Same ID Using JavaScript's getElementById()

Despite the rule that HTML elements should have unique IDs, you may encounter situations where elements have duplicate IDs due to external factors, such as API documentation. In such cases, obtaining a collection of these elements using JavaScript's getElementById() function can be challenging.

Instead of relying solely on getElementById(), which only returns the first matching element, you can utilize querySelectorAll() to retrieve multiple elements with the same ID. Here's how you can achieve this:

var elms = document.querySelectorAll("[id='duplicateID']");

// Iterate through the elements and perform necessary actions
for (var i = 0; i < elms.length; i++) {
  elms[i].style.display = 'none'; // For example, hiding the elements
}

This code will provide you with an array of elements with the specified ID, allowing you to manipulate or alter their properties as needed.

The above is the detailed content of How to Work with Multiple Elements with the Same ID in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn