Home > Article > Web Front-end > How to Work with Multiple Elements with the Same ID in JavaScript?
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!