Home > Web Front-end > JS Tutorial > How do I retrieve elements by class name in JavaScript?

How do I retrieve elements by class name in JavaScript?

Mary-Kate Olsen
Release: 2024-11-03 02:41:29
Original
602 people have browsed it

How do I retrieve elements by class name in JavaScript?

Retrieving Elements by Class Name

In JavaScript, obtaining an element by its ID is achieved through the document.getElementById("element-id") method. However, when attempting to access an element by its class name using document.getElementByClass("class-name"), an error возникает.

Solution: getElementsByClassName()

The correct syntax to retrieve elements based on their class name is document.getElementsByClassName("class-name"). This method returns a NodeList, containing all elements that share the specified class. To access a specific element within the NodeList, use its index, such as y[0] to access the first matching element.

Converting to an Array

If you require the NodeList to be represented as an array, you can do so by utilizing the Array.prototype.slice.call() method:

var arrFromList = Array.prototype.slice.call(y);
Copy after login

Alternative Approaches

Consider using the querySelectorAll('.foo') or querySelector('.foo') methods instead, as they provide better browser support.

Additional Considerations

  • For accurate information on DOM manipulation, refer to MDN rather than W3Schools.

The above is the detailed content of How do I retrieve elements by class name 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