JavaScript getElementsByClassName() Method

You are Here:

JavaScript getElementsByClassName() Method

The getElementsByClassName() method returns all elements whose class attribute matches the specified string.

Note: When called on the document object, the complete document is searched, including the root node.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <h2 class="point"></h2> <p class="point"></p> <script> var x = document.getElementsByClassName("point"); var txt = "<strong> Hello there! </strong>"; //Try to change "0" to "1" x[0].innerHTML = txt; </script> </body> </html>

Syntax

document.getElementsByClassName(className)

Parameter Values

ValueTypeExplanation
classNameRequiredThe class name of the elements you want to get.

More Examples

In the following example, we will apply CSS to the first element with a className point.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <h2 class="point">Heading</h2> <p class="point">Paragraph</p> <script> var x = document.getElementsByClassName("point"); x[0].style.color = "green"; </script> </body> </html>

In the following example, we will apply CSS to all elements with a className point.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <h2 class="point">Heading</h2> <p class="point">Paragraph</p> <script> var x = document.getElementsByClassName("point"); for(var i=0; i<x.length; i++) x[i].style.color = "green"; </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author