Document Object Model (DOM)


If you are new to DOM, you can get some knowledge at http://www.w3schools.com/htmldom/default.asp

Study on the following topics

Understand Parent, Children, Siblings and its hierarchical relationship.

Let me directly show few techniques to access the elements of the page using dojo.
The DOM nodes can be accessed by using its
  1. ID
  2. TagName
  3. Class
  4. Node Relationships

We will see each one of this with examples in the following topics.

Using ID:
To access an element using its ID, dojo provides two base methods
dojo.byId("just_the_id_of_element");
dojo.query("#followed_by_id_of_element");
If you know jquery, at this point of time, for easy understanding, consider dojo.query is similar to jQuery ie $("#followed_by_id_of_element");

Using TagName:
dojo.query("tagName");

Using Class:
dojo.query(".class_Name");

I will deal with node relationships in the next lesson. Let me show an example to access elements using ID, TagName and Class.

Code:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Tech Prem - Dojo Lesson-2</title>
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6.0/dojo/dojo.xd.js" type="text/javascript"></script>
<script type="text/javascript">
dojo.ready(function()
{
  dojo.require("dojo.NodeList-manipulate");
  dojo.query("input").onclick(function(){
 dojo.query("p").text("The content changed after click of the button");
 dojo.style(dojo.byId("firstID"),"color","red");
 dojo.query(".firstClass").style("width","150px");
  });
});
</script>
<style type="text/css">
#firstID {color:#666;}
.firstClass {width:100px; height:50px; background-color:#9C6;}
</style>
</head>
<body>
<p>Initial Content in P tag</p>
<div id="firstID">My Color will Change to red</div><br />
<div class="firstClass">This box will grow...</div><br />
<input type="button" value="Access DOM" />
</body>
</html>


Code Explained:

dojo.query("p").text("The content changed after click of the button");
The "P" tag accessed using the tag name. To use text method, it is required to include NodeList-manipulate. So I have included it by using dojo.require.

dojo.style(dojo.byId("firstID"),"color","red");
The color of the text inside the div with ID="firstID" has been changed by accessing the div using byId method.


dojo.query(".firstClass").style("width","150px");
The width of the div has been set to 150px by accessing the div using its class attribute "firstClass".



No comments:

Post a Comment

Please post your comments to help you and others better.