Change the HTML content of the first <li> element (index 0) in a list:
Before changing the text:
After changing the text:
The getElementsByTagName() method returns a collection of an elements's child elements with the specified tag name, as a NodeList object.
The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.
Tip: You can use the length property of the NodeList object to determine the number of child nodes with the specified tag name, then you can loop through all nodes and extract the info you want.
Tip: The parametervalue "*" returns all of the element's child elements.
The numbers in the table specifies the first browser version that fully supports the method.
Method | |||||
---|---|---|---|---|---|
getElementsByTagName() | 1.0 | 6.0 | 3.0 | 3.0 | 9.5 |
Parameter | Type | Description |
---|---|---|
tagname | String | Required. The tagname of the child elements you want to get |
DOM Version | Core Level 1 Element Object |
---|---|
Return Value: | A NodeList object, representing a collection of the element's child elements with the specified tagname. The elements in the returned collection are sorted as they appear in the source code. |
Find out how many <p> elements there are inside a <div> element (using the length property of the NodeList object):
The result of x will be:
Change the background color of the second <p> element (index 1) inside a <div> element:
Change the background color of all <p> elements inside a <div> element:
Change the background color of the fourth element (index 3) inside a <div> element:
Using the "*" parameter.
Change the background color of all elements inside a <div> element:
JavaScript Reference: document.getElementsByTagName()
JavaScript Tutorial: JavaScript HTML DOM Node List