|
JavaScript : Document Object Model
A document object model (DOM) is an application programming interface(API)
for represnting a document (such as HTML document) and accessing and manipulating
the various elements (such as HTML tags and strings of text) that makes up that document.
Representing Document as Tree
In DOM a web page is represented as a tree of nodes. For example,
here's the markup for a simple HTML page
<html>
<head>
<title>My Web Page</title>
</head>
<body>
<h1 class="MyClass">JavaScript Introduction</h1>
</body>
</html>
HTML documents have a hierarchical structure that is represented in the DOM as
a tree structure.
Document
|
HTML
__________________|______________
| |
HEAD BODY
| |
TITLE H1
| |
"My Page" "JavaScript Introduction"
In this tree, Document is a DOM Document node, while HTML, HEAD, BODY, TITLE and H1 are
all DOM Element nodes, and "My Web Page" and "JavaScript Introduction" are DOM Text nodes.
The H1 element node has a DOM Attribute node associated with it,
which has a name of "class" and a value of "intro".
Elements, Attributes and Text Nodes
AEvery part of a Web page is represented in the DOM by a node.
The most common nodes you'll encounter are element nodes, attribute nodes,
and text nodes. In addition, the whole document is represented by a document node.
Consider the following HTML markup:
<h1 class="MyClass">JavaScript Introduction</h1>
In the above example, the h1 element is a DOM Element node, the class attribute is a DOM Attribute node,
and the "JavaScript Introduction" text is a DOM Text node.
getElementByName: We can use getElementByName to obtain a list of any
type of HTML element.
<html>
<head>
<script type="text/javascript">
function showValue()
{
var x=document.getElementsByTagName("h1");
alert("This document have " + x.length + " h1 tag.")
}
</script>
</head>
<body>
<h1 id="myHeader" >JavaScript Tutorial</h1>
<h1 id="myHeader" >JavaScript Example</h1>
<h1 id="myHeader" >JavaScript Introduction</h1>
<p onclick="showValue()">Click on me</p>
</body>
</html>
getElementById: We can use getElementById to obtain a single HTML element with
the matching id attribute.
<html>
<head>
<script type="text/javascript">
function showValue()
{
var x=document.getElementById("myHeader");
alert(x.innerHTML);
}
</script>
</head>
<body>
<h1 id="myHeader" onclick="showValue()">JavaScript Tutorial</h1>
<p>Click on JavaScript Tutorial</p>
</body>
</html>
|