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

How to Select Elements by Class Name in JavaScript?

Mary-Kate Olsen
Release: 2024-11-03 17:03:02
Original
704 people have browsed it

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");
Copy after login

However, attempting to retrieve elements by class with the following syntax will result in an error:

var y=document.getElementByClass("by_class");
Copy after login

Solution:

To successfully retrieve elements by class, utilize the getElementsByClassName function instead:

var y = document.getElementsByClassName('foo');
Copy after login

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!

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