- JavaScript Basics
- JS Home
- JS Syntax
- JS Placements
- JS Output
- JS Statements
- JS Keywords
- JS Comments
- JS Variables
- JS var
- JS let
- JS const
- JS var Vs let Vs const
- JS Operators
- JS Arithmetic Operators
- JS Assignment Operators
- JS Comparison Operators
- JS Logical Operators
- JS Bitwise Operators
- JS Ternary Operator
- JS Operator Precedence
- JS Data Types
- JS typeof
- JS Conditional Statements
- JS Conditional Statement
- JS if Statement
- JS if...else Statement
- JS switch Statement
- JS Loops
- JS for Loop
- JS while Loop
- JS do...while Loop
- JS break Statement
- JS continue Statement
- JS break Vs. continue
- JavaScript Popup Boxes
- JS Dialog Box
- JS alert Box
- JS confirm Box
- JS prompt Box
- JavaScript Functions
- JS Functions
- JS setTimeout() Method
- JS setInterval() Method
- JavaScript Events
- JS Events
- JS onclick Event
- JS onload Event
- JS Mouse Events
- JS onreset Event
- JS onsubmit Event
- JavaScript Arrays
- JS Array
- JS Find Length of Array
- JS Add Elements at Beginning
- JS Add Element at End
- JS Remove First Element
- JS Remove Last Element
- JS Get First Index
- JS Get Last Index
- JS Reverse an Array
- JS Sort an Array
- JS Concatenate Arrays
- JS join()
- JS toString()
- JS from()
- JS Check if Value Exists
- JS Check if Array
- JS Slice an Array
- JS splice()
- JS find()
- JS findIndex()
- JS entries()
- JS every()
- JS fill()
- JS filter()
- JS forEach()
- JS map()
- JavaScript Strings
- JS String
- JS Length of String
- JS Convert to Lowercase
- JS Convert to Uppercase
- JS String Concatenation
- JS search()
- JS indexOf()
- JS search() Vs. indexOf()
- JS match()
- JS match() Vs. search()
- JS replace()
- JS toString()
- JS String()
- JS includes()
- JS substr()
- JS Slice String
- JS charAt()
- JS repeat()
- JS split()
- JS charCodeAt()
- JS fromCharCode()
- JS startsWith()
- JS endsWith()
- JS trim()
- JS lastIndexOf()
- JavaScript Objects
- JS Objects
- JS Boolean Object
- JavaScript Math/Number
- JS Math Object
- JS Math.abs()
- JS Math.max()
- JS Math.min()
- JS Math.pow()
- JS Math.sqrt()
- JS Math.cbrt()
- JS Math.round()
- JS Math.ceil()
- JS Math.floor()
- JS Math.trunc
- JS toFixed()
- JS toPrecision()
- JS Math.random()
- JS Math.sign()
- JS Number.isInteger()
- JS NaN
- JS Number()
- JS parseInt()
- JS parseFloat()
- JavaScript Date and Time
- JS Date and Time
- JS Date()
- JS getFullYear()
- JS getMonth()
- JS getDate()
- JS getDay()
- JS getHours()
- JS getMinutes()
- JS getSeconds()
- JS getMilliseconds()
- JS getTime()
- JS getUTCFullYear()
- JS getUTCMonth()
- JS getUTCDate()
- JS getUTCDay()
- JS getUTCHours()
- JS getUTCMinutes()
- JS getUTCSeconds()
- JS getUTCMilliseconds()
- JS toDateString()
- JS toLocaleDateString()
- JS toLocaleTimeString()
- JS toLocaleString()
- JS toUTCString()
- JS getTimezoneOffset()
- JS toISOString()
- JavaScript Browser Objects
- JS Browser Objects
- JS Window Object
- JS Navigator Object
- JS History Object
- JS Screen Object
- JS Location Object
- JavaScript Document Object
- JS Document Object Collection
- JS Document Object Properties
- JS Document Object Methods
- JS Document Object with Forms
- JavaScript DOM
- JS DOM
- JS DOM Nodes
- JS DOM Levels
- JS DOM Interfaces
- JavaScript Cookies
- JS Cookies
- JS Create/Delete Cookies
- JavaScript Regular Expression
- JS Regular Expression
- JS RegEx .
- JS RegEx \w and \W
- JS RegEx \d and \D
- JS RegEx \s and \S
- JS RegEx \b and \B
- JS RegEx \0
- JS RegEx \n
- JS RegEx \xxx
- JS RegEx \xdd
- JS RegEx Quantifiers
- JS RegEx test()
- JS RegEx lastIndex
- JS RegEx source
- JavaScript Advance
- JS Page Redirection
- JS Form Validation
- JS Validations
- JS Error Handling
- JS Exception Handling
- JS try-catch throw finally
- JS onerror Event
- JS Multimedia
- JS Animation
- JS Image Map
- JS Debugging
- JS Browser Detection
- JS Security
- JavaScript Misc
- JS innerHTML
- JS getElementById()
- JS getElementsByClassName()
- JS getElementsByName()
- JS getElementsByTagName()
- JS querySelector()
- JS querySelectorAll()
- JS document.write()
- JS console.log()
- JS instanceof
- JavaScript Programs
- JavaScript Programs
JavaScript getElementsByClassName()
The JavaScript getElementsByClassName() method returns an object similar to an array, representing all elements that have specified class name. For example:
<!DOCTYPE html> <html> <body> <p>The value is <span class="x"></span>.</p> <p>The value is <span class="x"></span>.</p> <p>The value is <span class="x"></span>.</p> <script> var elements = document.getElementsByClassName("x"); var totElements = elements.length; for(var i=0; i<totElements; i++) { elements[i].innerHTML = 10; } </script> </body> </html>
The value is .
The value is .
The value is .
In above example, the following statement:
var elements = document.getElementsByClassName("x");
returns all the three P (paragraph) elements, whose class name is same, that is x, and initialized to the elements variable as an array-like object. Now using the following statement:
var totElements = elements.length;
the length of elements will be initialized to totElements variable. Because elements carry total three elements, therefore 3 will be initialized to totElements variable. And using its indexes, I've set 10 as the content of all P elements, one by one, using for loop.
The above example can also be written as:
<!DOCTYPE html> <html> <body> <p>The value is <span class="myClass"></span>.</p> <p>The value is <span class="myClass"></span>.</p> <p>The value is <span class="myClass"></span>.</p> <script> var elems = document.getElementsByClassName("myClass"); for(var i=0; i<elems.length; i++) elems[i].innerHTML = 10; </script> </body> </html>
JavaScript getElementsByClassName() Syntax
The syntax of getElementsByClassName() method in JavaScript, is:
getElementsByClassName(className)
It returns an array-like object containing all elements having same specified className.
JavaScript getElementsByClassName() Example
Here is an example of getElementsByClassName() method in JavaScript:
<!DOCTYPE html> <html> <body> <p class="fresherearth">This is para one</p> <p class="fresherearth">This is para two</p> <p class="fresherearth">This is para three</p> <script> var elems = document.getElementsByClassName("fresherearth"); for(var i=0; i<elems.length; i++) { elems[i].style.fontSize = "1.5em"; elems[i].style.backgroundColor = "red"; elems[i].style.color = "whitesmoke"; elems[i].style.padding = "12px"; } </script> </body> </html>
This is para one
This is para two
This is para three
Now let me modify the above example in a way to pick multiple element(s) by its class names and styles it using JavaScript.
<!DOCTYPE html> <html> <body> <p class="a">This is para one</p> <p class="b">This is para two</p> <p class="a">This is para three</p> <p class="c">This is para four</p> <p class="d">This is para five</p> <p class="b">This is para six</p> <p class="a">This is para seven</p> <script> var elems = document.getElementsByClassName("a"); for(var i=0; i<elems.length; i++) { elems[i].style.fontSize = "1.5em"; elems[i].style.backgroundColor = "red"; elems[i].style.color = "whitesmoke"; elems[i].style.padding = "12px"; } var elems = document.getElementsByClassName("b"); for(var i=0; i<elems.length; i++) { elems[i].style.fontSize = "1.5em"; elems[i].style.backgroundColor = "purple"; elems[i].style.color = "whitesmoke"; elems[i].style.padding = "12px"; } var elems = document.getElementsByClassName("c"); for(var i=0; i<elems.length; i++) { elems[i].style.fontSize = "1.5em"; elems[i].style.backgroundColor = "blue"; elems[i].style.color = "whitesmoke"; elems[i].style.padding = "12px"; } var elems = document.getElementsByClassName("d"); for(var i=0; i<elems.length; i++) { elems[i].style.fontSize = "1.5em"; elems[i].style.backgroundColor = "#ccc"; elems[i].style.color = "whitesmoke"; elems[i].style.padding = "12px"; } </script> </body> </html>
This is para one
This is para two
This is para three
This is para four
This is para five
This is para six
This is para seven
In above example, let me explain the following JavaScript code:
var elems = document.getElementsByClassName("a"); for(var i=0; i<elems.length; i++) { elems[i].style.fontSize = "1.5em"; elems[i].style.backgroundColor = "red"; elems[i].style.color = "whitesmoke"; elems[i].style.padding = "12px"; }
In above block of code, the statement:
var elems = document.getElementsByClassName("a");
initializes an array-like object that have the class name a, to the variable elems. Therefore, now:
- elems[0] indicates to first P tag having class name a. That is, <p class="a">This is para one</p>
- elems[1] indicates to second P tag having class name a
- elems[2] indicates to third P tag having class name a
And using the for loop, I've applied the style to all these three paragraphs, using JavaScript.
In similar way, the process goes for next three classes, that are b, c, and d.
Since the following three JavaScript codes (responsible to change the style):
- elems[i].style.fontSize = "1.5em";
- elems[i].style.color = "whitesmoke";
- elems[i].style.padding = "12px";
are similar to all, therefore let me wrap these, into a function, in this way:
<!DOCTYPE html> <html> <body> <p class="a">This is para one</p> <p class="b">This is para two</p> <p class="a">This is para three</p> <p class="c">This is para four</p> <p class="d">This is para five</p> <p class="b">This is para six</p> <p class="a">This is para seven</p> <script> function changeStyle(element) { element.style.fontSize = "1.5em"; element.style.color = "whitesmoke"; element.style.padding = "12px"; } var elems = document.getElementsByClassName("a"); for(var i=0; i<elems.length; i++) { elems[i].style.backgroundColor = "red"; changeStyle(elems[i]); } var elems = document.getElementsByClassName("b"); for(var i=0; i<elems.length; i++) { elems[i].style.backgroundColor = "purple"; changeStyle(elems[i]); } var elems = document.getElementsByClassName("c"); for(var i=0; i<elems.length; i++) { elems[i].style.backgroundColor = "blue"; changeStyle(elems[i]); } var elems = document.getElementsByClassName("d"); for(var i=0; i<elems.length; i++) { elems[i].style.backgroundColor = "gray"; changeStyle(elems[i]); } </script> </body> </html>
If you already know, that the document has a single element with specified or given class name, then you can directly proceed like:
<!DOCTYPE html> <html> <body> <p>The value is <span class="cc"></span>.</p> <script> document.getElementsByClassName("cc")[0].innerHTML = 10; </script> </body> </html>
The value is .
Get Elements by Class Name inside an Element in JavaScript
To access or get only those elements with specified class name, that are inside some particular element. That is, to get all elements having redTxt class, that are available in an element with id value myDiv, use the following code:
document.getElementById('myDiv').getElementsByClassName('redTxt')
For example:
<!DOCTYPE html> <html> <body> <p class="redTxt">This is para one</p> <div id="myDiv"> <p class="redTxt">This is para two</p> <p class="redTxt">This is para three</p> </div> <p class="redTxt">This is para four</p> <script> var elems = document.getElementById('myDiv').getElementsByClassName('redTxt'); for(i=0; i<elems.length; i++) { elems[i].style.color = "red"; } </script> </body> </html>
This is para one
This is para two
This is para three
This is para four
See the output, only elements with class redTxt, available inside another element with id myDiv, will be applied red colored style to it.
And if you want to get first element with specified class name, available inside another element having some specified value like id, then proceed in this general way:
document.getElementById('myDiv').getElementsByClassName('redTxt')[0]
Get All Elements with Two Given Class Names
To get all elements having any two classes say red and x, then use the following JavaScript code:
document.getElementsByClassName('red x')
« Previous Tutorial Next Tutorial »