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
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!