Home > Web Front-end > JS Tutorial > How Can I Replace HTML Element Content Using JavaScript and Class Names?

How Can I Replace HTML Element Content Using JavaScript and Class Names?

Barbara Streisand
Release: 2024-12-05 07:24:13
Original
900 people have browsed it

How Can I Replace HTML Element Content Using JavaScript and Class Names?

How to Access and Modify HTML Elements by Class in JavaScript

Obtaining elements by class in JavaScript differs from using IDs due to JavaScript's lack of an in-built function for this purpose. However, a workaround can be implemented.

To modify the content within an HTML element using a class instead of an ID, you can utilize the following code:

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

This code iterates through all elements in the document and checks if their class list contains the specified matchClass. Upon finding a match, it replaces the content of that element with the provided content parameter.

This approach ensures compatibility across browsers. Here's a practical example:

replaceContentInContainer('box', 'This is the replacement text');
Copy after login
<div class='box'></div>
Copy after login

This code replaces the content of the

with the specified text.

The above is the detailed content of How Can I Replace HTML Element Content Using JavaScript and Class Names?. 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