Home >Web Front-end >JS Tutorial >Can You Retrieve Elements with Duplicate IDs Using getElementById()?
Overcoming Duplicate IDs with getElementById
Question:
How do you retrieve a collection of elements with the same ID using solely getElementById()?
Answer:
Using getElementById() to retrieve multiple elements with the same ID violates HTML standards. However, if faced with such an invalid HTML structure, an alternative approach is to utilize querySelectorAll() as follows:
var elements = document.querySelectorAll("[id='duplicateID']"); for (var i = 0; i < elements.length; i++) { // Perform actions on each element, e.g., modify styles: elements[i].style.display = 'none'; }
By employing this method, you can navigate an invalid HTML structure containing duplicate IDs and apply desired effects to each matching element. Note that the provided code is intended as a workaround for handling invalid HTML and should not be considered a recommended practice for building valid HTML documents.
The above is the detailed content of Can You Retrieve Elements with Duplicate IDs Using getElementById()?. For more information, please follow other related articles on the PHP Chinese website!