Home > Web Front-end > JS Tutorial > body text

How can I retrieve multiple elements with the same ID using getElementById() in JavaScript?

Barbara Streisand
Release: 2024-11-23 21:53:11
Original
906 people have browsed it

How can I retrieve multiple elements with the same ID using getElementById() in JavaScript?

Retrieving Multiple Elements with Same ID Using getElementById

In JavaScript, getElementById is a powerful method for selecting elements based on their unique IDs. However, what happens when you encounter multiple elements sharing the same ID, which is invalid HTML but sometimes unavoidable?

The following question addresses this scenario:

Question: How can I obtain a collection of elements by specifying their ID attribute, including those with duplicate IDs? I want to use only getElementById() to achieve this.

Answer:

While using getElementById() for elements with duplicate IDs is not ideal, there are ways to work around this issue. One approach is to use querySelectorAll:

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

for(var i = 0; i < elms.length; i++) 
  elms[i].style.display='none';
Copy after login

This code retrieves all elements with the specified ID and stores them in an array named elms. You can then iterate through the array and perform any desired actions on each element, such as hiding them in the example above.

Note that using getElementById() for elements with duplicate IDs can lead to unpredictable behavior. It's generally recommended to enforce valid HTML by using unique IDs for elements.

The above is the detailed content of How can I retrieve multiple elements with the same ID using getElementById() in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template