Home >Web Front-end >JS Tutorial >How Can I Efficiently Get and Manipulate Elements by Class Name in Vanilla JavaScript?
Get Elements by Class in JavaScript: A Comprehensive Solution
The absence of an inbuilt get elements by class function in JavaScript poses a challenge for developers who need to manipulate elements based on class attributes. In this article, we will explore an effective method for retrieving elements by class using vanilla JavaScript.
A Tale of Two Approaches: IDs vs. Classes
Traditionally, elements have been accessed via unique IDs using the getElementById() function. However, when dealing with multiple elements, IDs become impractical. Classes, on the other hand, allow for flexible grouping of elements.
Introducing the Solution
To overcome this limitation, we present a comprehensive function called replaceContentInContainer(). This function takes two parameters: a class name and the replacement content. Here's how it operates:
Code Implementation:
function replaceContentInContainer(matchClass, content) { var elems = document.getElementsByTagName('*'), i; for (i in elems) { if((' ' + elems[i].className + ' ').indexOf(' ' + matchClass + ' ') > -1) { elems[i].innerHTML = content; } } }
Example Usage:
replaceContentInContainer('box', 'This is the replacement text');
This revised solution enables efficient and flexible replacement of content within elements based on their class attributes.
Additional Notes:
The above is the detailed content of How Can I Efficiently Get and Manipulate Elements by Class Name in Vanilla JavaScript?. For more information, please follow other related articles on the PHP Chinese website!