1. Technology

JavaScript By Example

Document Object Model: 2. Get Nodes For A Tag Name


We do not need to have attributes such as id on the tags inur web page in order to be able to access them from JavaScript. There are a number of different ways thatwe can access collections of tags within the web page from JavaScript. These collections are known as nodelists and while they are to some extent similar to arrays in the way that we can reference individual nodes and the length of the list they are not actually arrays because they do not have any of the other properties and methods associated with arrays (unless we copy the nodelist into an array first).

The simplest command for retrieving a nodelist rather than an individual node is the getElementsByTagName method which returns a nodelist of all of the tags in the doculent of a particular type. For example the following code will establish a nodelist of all the paragraph tags within the web page allowing us to loop through the nodes to update every paragraph in the page.


<title>Example D02</title>
<script type="text/javascript" src="exampleD02.js"></script>


var node; node = document.getElementsByTagName('p');
for (var i = node.length-1; i>=0; i--) {
node[i].innerHTML = 'hello world';

  1. About.com
  2. Technology
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. Document Object Model
  7. JavaScript By Example - DOM: Get Nodes For A Tag Name

©2014 About.com. All rights reserved.