For traversing the DOM tree there is an object Element which can have various properties using which the Document tree can be traversed. In other words suppose we have written some XHTML web document and if we want to check what are the elements in that web document or if we want to check which is the first element in that web document then such queries can be solved by allowing the designer to walkthrough the web document. For traversing such tree simple JavaScript can be written. Following is an illustration in which we have a form object which we have placed three elements such as button, text box and submit button. As an output we can obtain of these elements.
Example Program
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>DOM Tree Traversal</title>
<script type="text/javascript">
function my_fun()
{
var Dom_obj=document.getElementById("form1");
alert(Dom_obj.nodeName);
alert("There are "+Dom_obj.length+" elements of form element and those are");
for(i=0;i<Dom_obj.length;i++)
alert("Element Type: "+Dom_obj.elements[i].type+"\n"+"Element Value:"+Dom_obj.elements[i].value);
}
</script>
</head>
<html>
<body>
<center>
<form id="form1">
<input type="button" value="OK"/><br/>
<br/><br/>
<input type="text" value="Hello" id="mytext"/>
<br/><br/>
<input type="submit" value="Click here to get the HTML elements" onclick="my_fun();"/>
</form>
<p><em>
</em></p>
</center>
</body>
</html>
Output in Browser
We can use various properties such as nextSibling, firstChild, lastChild and so on in order to traverse through the DOM tree. In above give script we have used simple properties such as nodeName, value and type to access the particular node.
We can also modify the existing structure of DOM tree by removing some child or replacing one child by another child. For that purpose replaceChild properties is used.
0 comments:
Post a Comment