1. Computing & Technology

JavaScript By Example

Document Object Model: 1. Get An id Node

From , former About.com Guide

The Document Object Model provides a series of commands through which JavaScript can access the HTML in your web page. There are a number of commands in the document object model that will return a node or nodelist that basically point to one or more tags (or the text within a tag) within the web page. Any actions that we perform on the node or nodelist will update the corresponding tags (or text) in the HTML. All of the document object model commands are methods of the document object which we can consider to be the mechanism by which JavaScript can interact with the content of the web page itself.

The simplest and most common way that you reference a node (or tag) in your HTML from JavaScript is where the HTML tag has an id associated with it. The getElementById method returns a reference to the specific node in the web page that has the id that we have specified. Since an id must be unique within a web page this call will either return the specific node having that id if there is one in the page or will be undefined if no such id exists in the page.

The very first of the introductory examples where we looked at how best to attach JavaScript to our page used this method to access the div within the page into which we wanted to insert some text.

HTML


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Example D01</title>
</head>
<body>
<div id="ex"></div>
<script type="text/javascript" src="exampleD01.js"></script>
</body>
</html>

JavaScript


document.getElementById('ex').innerHTML = 'hello world';

©2012 About.com. All rights reserved.

A part of The New York Times Company.