Power of Document Object Model (DOM) is often overlooked in web interface design, DOM could be lifesaver for developers if correctly used.
We will be writing series of articles from basics to advanced usage of DOM, this part of article will introduce basis of DOM/Javascript.
Basics of elements, attributes and events
In simple words, a web page acts as containers of different elements like links, divs, images etc. You can related element to object, if you have worked in OOP, just like object each element is contained in its parent elements and can have some child elements, as well as some properties.
For example, we have login form named as loginFrm in our document, with text field for user name named ‘user_name’ and password field. To access the user name field we have to write:
document.loginFrm.user_name , where document is main container document that holds form and form holds all fields as its child tags.
As mentioned above, each element has its own attributes, like fields elements has attribute of “value”, that is used to change the value of field. Similarly Divs has attribute “innerHTML”, which is used to update text in particular div.
For a complete introduction about DOM please refer to http://en.wikipedia.org/wiki/Document_Object_Model.
Events
Javascript is capable to detect and associate user interactivity with document elements, these events can be used to perform different operations for example changing image when mouse moves over, calling validation function when form is submitted. Showing some alert when certain element is clicked.
Some events are listed below:
- OnMouseOver
- OnMouseOut
- OnBlur
- OnFocus
- OnClick
Methods to access elements :
- getElementsByTagName
Writing document.getElementsByTagNames('table') will return all tables in document as an array. Then we can loop to interact with returned elements.
- getElementById
document.getElementById() will return one single element that has id value, passed as parameter. For example we can access user name field through :
document.getElementById('user_name');
How to debug
First thing we tell our developers is to use FireFox while working with javascript. Its error console helps detecting errors with ease. Identifying the error is first step to find a cure.
Some of most common mistakes while working with DOM are :
- Duplicate ID or Name, this is very important to uniquely identify your elements if you are using document.getElementById.
- Javascript is case sensitive, make sure you call functions and ids in correct case. Best practice is to follow some naming conventions, two common conventions are either use underscore or capitalize new letter. For example in case of field name, label it as ‘user_name’ or ‘userName’. Following some conventions will help you reduce debugging time.
Next page has basic example that will help you get started.
Pages: 1 · 2
Recent comments