Getting hold of objects in Javascript via methods is quite easy, only when the objects are given proper attributes. Here is a small guide, which you might want to take a look at, before writing some javascript code.
First take a look at elements and proper naming of attributes, and then follow it with a standard list of methods.
1. When using a input tag or element in your page, it is better you put it inside a form tag.
<input type = “text” name = “username”>
will suffice if you want to get the value of the username in the next page. But it is very good practice, to use a id attribute the same as the name. Also, though not required, it is better you close the input tag (a standard in xhtml).
<form id = “loginForm” name = “loginForm” method = “post” action = “process.php”>
<INPUT TYPE=”text” NAME=”username” id = “username” size = “20″ maxlength = “15″/>
</form>
1. Use a form tag and put all your input fields inside.
2. Give a name and a id to your form, and let both be same, as far as possible.
3. Give a end tag to your input tag.
4. Use size and maxlength properties in your text boxes.
5. Put your form inside a div, and use a id and a name for your div also.
Now let us take a look at the actual methods.
1. getElementById (’theIdNameGoesHere’) - This method will return a node of the item, which has the id specified in the input parameter. This is the most used and convenient way to access a node. It can be used only when the id attribute is specified. Hence if you are using a script on your page, make sure all your elements are given proper id attribute.
var myForm = document.getElementById (’loginForm’);
2. getElementsByTagName (’tagName’) - This method is usually used, when the the id attribute is not specified. Assume there is a form tag in the code, but it does not hold a id attribute, you may use this function. Remember that this function returns a array of objects or nodes. It is the developer’s responsibility to get hold of the appropriate object int he array.
var myFormArray = document.getElementsByTagName (’form’);
var myForm = myFormArray (0);
3. getElementsByClassName (className) - Notice the s in the elements. This function returns all elements with the class name specified as the input. This may not be considered a standard function, but mozilla project uses a lot of this function in many places in the firefox code. As again, this object returns a object.
All these functions can be called upon the document element, which is the root element as well as any other element. Here is an example. We have the form object by means of the getElementById (’loginForm’) method, now we can get the inout box inside by
var inputBox = myForm.getElementsByTagName (’input’);
Any questions or need more help, ask coder at codeinsane.com




No user commented in " javascript methods to get elements "
Follow-up comment rss or Leave a TrackbackLeave A Reply - Opinionate..