HTMLCollection length Property
The length() Property is used to return the collection of all HTML elements in a document. It is read-only property and is quite useful when a user wants to loop through an HTML Collection.
Syntax:
HTMLCollection.length
Return Value: It returns a number which represent the number of all elements in a HTML Collection.
Below example shows how to count the all <p> element in the html collection:
Example-1:
HTML
<!DOCTYPE html> < html > < head > < style > h1 { color: green; } </ style > </ head > < body > < center > < h1 >w3wiki</ h1 > < h2 > HTMLCollection length Property </ h2 > < p > The length property is used to return the number of all elements in a HTMLCollection. </ p > < div > < p >w3wiki</ p > < p >A Computer science portal for Beginner</ p > </ div > < button onclick = "Beginner()" >Submit</ button > <!-- l is the HTML collection here --> < script > function Beginner() { var l = document.getElementsByTagName("P").length; alert(l); } </ script > </ center > </ body > </ html > |
Output:
Before clicking on the button:
After clicking on the button:
Example-2: To highlight all the elements with class GFG using length property.
HTML
<!DOCTYPE html> < html > < head > < style > h1 { color: green; } </ style > </ head > < body > < center > < h1 >w3wiki</ h1 > < h2 >HTMLCollection length Property</ h2 > < p > The length property is used to return the number of all elements in a HTMLCollection. </ p > < div > < p class = "GFG" >w3wiki</ p > < p class = "GFG" > A Computer science portal for Beginner </ p > </ div > < button onclick = "Beginner()" >Submit</ button > <!-- w is the HTML collection here --> < script > function Beginner() { var w, c; w = document.getElementsByClassName("GFG"); for (c = 0; c < w.length ; c++) { w[c] .style.backgroundColor = "BLUE" ; } } </script> </ center > </ body > </ html > |
Output:
Before clicking on the button:
After clicking on the button:
Supported Browsers: The browser supported by HTMLCollection length property are listed below:
- Google Chrome 1
- Edge 12
- Internet Explorer 8
- Firefox 1
- Opera 12.1
- Safari 1