There are several ways by which we can access the elements of the web document. To understand these methods of accessing we will consider one simple web document as follows-
XHTML Document
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>This is my Web Page</title>
</head>
<html>
<body>
<form name="form1">
<input type="text" name="myinput"/>
</form>
</body>
</html>
Method 1
Every XHTML document element is associated with some address. This address. This address called DOM address. The document has the collection of forms and elements. Hence we can refer the text box element as-
var Dom_Obj=document.forms[0].elements[0];
But this is not the suitable method of addressing the elements. Because if we change the above script as
....
<form name="form1">
<input type="button" name="mybutton"/>
<input type="text" name="myinput"/>
</form>
....
then index reference gets changed. Hence another approach of accessing the elements is developed.
Method 2
In this method we can make use of the name attribute in order to access the desired element.
var Dom_Obj=document.form1.myinput;
But this may cause a validation problem because the XHTML 1.1 standard does not support the name attribute to the form element. Hence another way of accessing is introduced.
Method 3
We can access the desired element from the web document using JavaScript method getElementById. This method is defined in DOM1. The element does access can be made as follows -
var Dom_Obj=document.getElementById("myinput")
But if the element is in particular group, that means if there are certain elements on the form such as radio buttons or check boxes then they normally appear in the groups. Hence to access these elements we make use of its index. Consider the following code sample
<form name="form1">
<input type="checkbox" name="vegetables" value"Spinach" />Spinach
<input type="checkbox" name="vegetables" value"FenuGreek" />FenuGreek
<input type="checkbox" name="vegetables" value"Cabbage" />Cabbage
</form>
For getting the values of these checkboxes we can write following code.
var Dom_Obj=document.getElementById("Food");
for(i=0;i<Dom_Obj.vegetables.length;i++)
document.write(Dom_Obj.vegetables[i]+"<br/>");
0 comments:
Post a Comment