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
Barbara StreisandOriginal
2024-12-05 07:24:13983browse

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;
        }
    }
}

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');
<div class='box'></div>

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!

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