In Javascript, the getElementsByClassName method is used to access HTML elements based on their class name.
This method returns a live HTMLCollection, which is similar to an array, containing all elements with the specified class name.
<script> var elements = document.getElementsByClassName('className'); </script>
className: It specifies the `className` of the HTML element we want to access either to fetch information or content modification.
Return value: If an element with the specified ID exists in the document (DOM), The `getElementById` function returns a reference to that element. Otherwise, it returns null.
Here, we have created HTML elements and added `class` attributes with the value "highlight".
<div class="highlight">This Content has to be 'changed'.</div> <p>This paragraph does not have the 'highlight' class.</p> <div class="highlight">This Content also needs to be 'Changed'.</div>
Here, in Script, we added the Script tag and the `getElementsByClassName` function.
<script> // Accessing elements with the class 'highlight' var elements = document.getElementsByClassName('highlight'); // Looping through the collection and modifying each element for (var i = 0; i < elements.length; i++) { elements[i].innerHTML = 'Content changed using JavaScript.'; } </script>
In the above example, we have updated all element's content which contains a class with the name `highlight`.
The `getElementsByClassName` method fetches a live HTML Collection containing all elements with the class name 'highlight'.
The script then loops through each element in the collection and modifies their content.
The `getElementsByClassName` method is used to obtain a reference to the HTML element with the `class` attribute set to 'highlight'.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>getElementsByClassName Example</title> <style> .highlight { color: blue; font-weight: 600; } </style> </head> <body> <div class="highlight">This Content has to be 'changed'.</div> <p>This paragraph does not have the 'highlight' class.</p> <div class="highlight">This Content also needs to be 'Changed'.</div> <script> // Accessing elements with the class 'highlight' var elements = document.getElementsByClassName('highlight'); // Looping through the collection and modifying each element for (var i = 0; i < elements.length; i++) { elements[i].innerHTML = 'Content changed using JavaScript.'; } </script> </body> </html>
In the above example, we have created multiple `div` elements with `class` as `highlight`.
In the Next Step, Inside the `Script` tag we try to access all elements whose `class` is `highlight`.
In the Next Lines, we are looping over the elements retrieved through `getElementByClassName` method and modifying the `content` of the elements.