With the DOM, you can access every node in an HTML document.
You can access a node in three ways:
The getElementById() method returns the element with the specified ID:
The following example gets the element with id="intro":
Note: The getElementById() method doesn't work in XML.
getElementsByTagName() returns all elements with a specified tag name.
The following example returns a nodeList of all <p> elements in the document:
The following example returns a nodeList of all <p> elements that are descendants of the element with id="main":
The getElementsByTagName() method returns a node-list. A node-list is an array of nodes.
The following code selects all <p> nodes in a node-list:
The nodes can be accessed by index number. To access the second <p> you can write:
Note: The index starts at 0.
You will learn more about node-lists in a later chapter of this tutorial.
The length property defines the number of nodes in a node-list.
You can loop through a node-list by using the length property:
Example explained:
The three properties; parentNode, firstChild, and lastChild, follow the document structure and allow short-distance travel in a document.
Look at the following HTML fragment:
In the HTML code above, the first p element is the first child node (firstChild) of the body element, and the div element is the last child node (lastChild) of the body element. The parent node (parentNode) of the first p element and the div element, is the the body element, and the parent node of the p elements inside the div element, is the div element.
The firstChild property can also be used to access the text of an element:
There are two special document properties that allow access to the tags:
| WEB HOSTING |
|---|
| Best Web Hosting |
| PHP MySQL Hosting |
| Best Hosting Coupons |
| UK Reseller Hosting |
| Cloud Hosting |
| Top Web Hosting |
| $7.95/mo SEO Hosting |
| Premium Website Design |
| WEB BUILDING |
|---|
| XML Editor - Free Trial! |
| FREE Website BUILDER |
| Free Website Templates Free CSS Templates |
| Make Your Own Website |
| W3SCHOOLS EXAMS |
|---|
|
Get Certified in: HTML, CSS, JavaScript, XML, PHP, and ASP |
| W3SCHOOLS BOOKS |
|---|
|
New Books: HTML, CSS JavaScript, and Ajax |
| STATISTICS |
|---|
|
Browser Statistics Browser OS Browser Display |
| SHARE THIS PAGE |
|---|