YouTip LogoYouTip

Js Htmldom Collections

# JavaScript HTML DOM Collection This chapter introduces the use of DOM collections. * * * ## HTMLCollection Object The getElementsByTagName() method returns an (#) object. An HTMLCollection object is an array-like list of HTML elements. The following code gets all

elements in the document: ## Example var x = document.getElementsByTagName("p"); Elements in the collection can be accessed by their index (starting from 0). To access the second

element, you can use the following code: y = x; [Try it Β»](#) * * * ## HTMLCollection Object length Property The length property of the HTMLCollection object defines the number of elements in the collection. ## Example var myCollection = document.getElementsByTagName("p"); document.getElementById("demo").innerHTML = myCollection.length; [Try it Β»](#) ### Example Explained Get the collection of

elements: var myCollection = document.getElementsByTagName("p"); Display the number of elements in the collection: document.getElementById("demo").innerHTML = myCollection.length; The collection length property is often used to loop through the elements in a collection. ## Example Change the background color of all

elements: var myCollection = document.getElementsByTagName("p"); var i; for(i = 0; i<myCollection.length; i++){myCollection.style.backgroundColor = "red"; } [Try it Β»](#) ### Note **HTMLCollection is NOT an array!** An HTMLCollection may look like an array, but it is not. You can access elements using an index, just like an array. An HTMLCollection cannot use array methods: valueOf(), pop(), push(), or join().

← Linux Comm XargsMet Document Adoptnode β†’