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
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!