YouTip LogoYouTip

Htmldom Navigation

# HTML DOM Navigation * * * With the HTML DOM, you can navigate through the node tree using node relationships. * * * ## HTML DOM Node List The getElementsByTagName() method returns a _node list_. A node list is an array of nodes. The following code selects all

nodes in the document: ## Example var x=document.getElementsByTagName("p"); You can access these nodes using index numbers. To access the second

, you can write: y=x; [Try it yourself Β»](#) **Note:** Index numbers start from 0. * * * ## HTML DOM Node List Length The length property defines the number of nodes in a node list. You can use the length property to loop through a node list: ## Example x=document.getElementsByTagName("p"); for(i=0;i<x.length;i++){document.write(x.innerHTML); document.write("
"); } [Try it yourself Β»](#) ### Example Explanation: * Get all

element nodes * Output the value of the text node of each

element * * * ## Navigating Node Relationships You can navigate through the document structure using three node properties: parentNode, firstChild, and lastChild. Consider the following HTML snippet:

Hello World!

DOM is very useful!

This example demonstrates node relationships.

* The first

element is the first child (firstChild) of the element * The

element is the last child (lastChild) of the element * The element is the parent node (parentNode) of both the first

element and the

element The firstChild property can be used to access an element's text: ## Example

Hello World!

x=document.getElementById("intro"); document.write(x.firstChild.nodeValue); [Try it yourself Β»](#) * * * ## DOM Root Nodes There are two special properties that provide access to the entire document: * document.documentElement - the entire document * document.body - the document body ## Example

Hello World!

DOM is very useful!

This example demonstrates the document.body property.

alert(document.body.innerHTML); [Try it yourself Β»](#) * * * ## childNodes and nodeValue In addition to the innerHTML property, you can also use the childNodes and nodeValue properties to retrieve element content. The following code retrieves the value of the

element with id="intro": ## Example

Hello World!

txt=document.getElementById("intro").childNodes.nodeValue; document.write(txt); [Try it yourself Β»](#) In the example above, getElementById is a method, while childNodes and nodeValue are properties. In this tutorial, we will use the innerHTML property. However, learning the methods above helps deepen your understanding of the DOM tree structure and navigation.
← Htmldom SummaryHtmldom Events β†’

YouTip © 2024-2026 | Home | Learn Technology, Build Dreams!

All content is for educational and learning purposes only.