If you want to select elements by class name then JavaScript DOM provides you a method called document.getElementsByClassName()
.
Using getElementsByClassName()
method, you can select all the HTML elements having the same class name.
let htmlElements = document.getElementsByClassName("class-name");
document.getElementsByClassName()
method accepts the class name of the HTML elements that you want to select. If the match is found, it returns a NodeList that you can treat as an array; otherwise, it returns null
.
In an HTML document, more than one HTML elements can have the same class name, so you need to use for
loop to iterate through all the HTML elements returned by the document.getElementsByClassName()
method.
HTML Code
<!DOCTYPE html> <html> <head> <title>JavaScript document.getElementsByClassName() Example</title> </head> <body> <div id="container"> <p class="main-section">First Paragraph.</p> <p class="main-section">Second Paragraph.</p> <p class="main-section">Third Paragraph.</p> </div> <script src="app.js"></script> </body> </html>
JavaScript Code: app.js
let paragraphs = document.getElementsByClassName('main-section'); for(let paragraph of paragraphs){ paragraph.style.margin='50px'; }
It is interesting to note that you can even use the document.getElementsByClassName()
method on the parent element to access the elements which are inside it.
Let's see how to use document.getElementsByClassName()
method with the parent element. The same code is rewritten with some modification.
JavaScript Code: app.js
let parent = document.getElementById('container'); let paragraphs = parent.getElementsByClassName('main-section'); for(let paragraph of paragraphs){ paragraph.style.margin='50px'; }
This code will produce the same output.