Home > Article > Web Front-end > How to Select Elements by Class Name in JavaScript?
How to Obtain Elements by Class Name in JavaScript
In JavaScript, obtaining elements by ID follows the syntax:
var x=document.getElementById("by_id");
However, attempting to retrieve elements by class with the following syntax will result in an error:
var y=document.getElementByClass("by_class");
Solution:
To successfully retrieve elements by class, utilize the getElementsByClassName function instead:
var y = document.getElementsByClassName('foo');
Considerations:
The return value is an array-like object (NodeList or HTMLCollection), not a single element. To access individual elements, use square bracket notation (y[0]).
Alternative Methods:
querySelector('.foo') and querySelectorAll('.foo') are preferred alternatives due to wider browser support (93.99% vs 87.24% for getElementsByClassName).
The above is the detailed content of How to Select Elements by Class Name in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!