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
Mary-Kate OlsenOriginal
2024-11-03 02:41:29612browse

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);

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!

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