Home > Web Front-end > JS Tutorial > How Can I Access Elements by Class in JavaScript?

How Can I Access Elements by Class in JavaScript?

Mary-Kate Olsen
Release: 2024-12-02 08:20:11
Original
449 people have browsed it

How Can I Access Elements by Class in JavaScript?

Accessing Elements by Class in JavaScript

JavaScript does not natively provide a getElementByClass() function. To access elements based on their class, you can use the following techniques:

1. Using getElementsByClassName():

This method returns a collection of elements with the specified class name. However, it is only supported in modern browsers and does not allow for nested or multiple classes.

Example:

const elements = document.getElementsByClassName("className");
Copy after login

2. Using getElementsByTagName('*') with Looping:

This approach iterates through all the elements on a page and checks their class list for a match. It works in all browsers, including older ones.

Example:

function replaceContentInContainer(matchClass, content) {
    const elems = document.getElementsByTagName('*');
    for (let i = 0; i < elems.length; i++) {
        if ((' ' + elems[i].className + ' ').indexOf(' ' + matchClass + ' ') > -1) {
            elems[i].innerHTML = content;
        }
    }
}
Copy after login

This revised code allows you to replace the contents of elements based on their class name, even if multiple elements on the page share the same class.

The above is the detailed content of How Can I Access Elements by Class 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