Home  >  Article  >  Web Front-end  >  How to Select Elements by Class Name in JavaScript?

How to Select Elements by Class Name in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 17:03:02652browse

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!

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
Previous article:Next.js AuthenticationNext article:Next.js Authentication