JavaScript DOM

Document Object Model or DOM is a Tree Like Structure of HTML Document, with connected nodes, as shown below. Everything on a webpage page is treated as a node, i.e. HTML tags, text inside, attributes and child tag. HTML Tag, (<HTML>) is the Root Node, and all other elements are descendant node of html tag. Even doctype and comments are also nodes.

JS DOM, document object modal
JavaScript Document Object Model ( DOM )

To access DOM Element, or Elements, document or window.document keyword is used.

DOM Methods

DOM Element Example


<h1 class="heading">Javascript <span>DOM</span></h1>
	
 h1         = Element Node
 class      = Attribute Node
 Javascript = Text Node
 span       = Child Node
 DOM        = Text Node

document.write

document.write() method is used to write something in current document or DOM node. If <script> tag is inside body, document.write() will write plain text in body node. But if <script> tag is in another element, like p, div etc, document.write() will write plain text in that p or div element node.

If webpage is already loaded, document.write() method will replace the current document.

Hello JS

document.write("Hello JS");

Hello JS in h1 tag


document.write("<h1>Hello JS in h1 tag</h1>");

Hello JS, with i tag in p.


document.write("<p>Hello JS, with <i>i tag</i> in p.</p>");

As document.write() method will replace the current document, we usually avoid using document.write() method.



Getting Elements from DOM

document method or window.document is used to excess any element on a webpage. These Method returns a node object or a node list( array like structure ).

document.body


 var x=document.body;
 x.nodeName		// return BODY
 

document.images


 var y=document.images;
 y.length       // return no of images
 y[0].nodeName  // return IMG
 y[0].nodeType  // return 1 
	

DOM Shortcut Methoods

Method Use
document.body To excess body element of webpage
document.images return list of all images in document.
document.links return list of all hyperlinks in document.
document.anchors return list of only anchor tags in document.
document.forms return list of form tags in document.
document.contact return form element with name="contact" in document.
<form name="contact"></form>
document.contact.username return form control with name="username" on contact form of document.
<form name="contact">
    <input type="text" name="username">
</form>

nodeType

Code Type
1 element
2 attribute
3 text
8 comment
9 document
10 doctype

document.body is node object. But document.images is array-like object. To access individual element inside list, use index notation. Exp, document.images[0] means first image of webpage.


Get Element By Id

document.getElementById() return the element with unique id that is given as an argument. It is supported in all major browsers. As per w3c specifications, id attribute and id's value is unique. Get Element By Id will call an element with his unique id.

<h1 id="heading">Javascript DOM</h1>
<script>    
 var x=document.getElementById("heading");
</script>

Get Elements By Tag Name

document.getElementsByTagName() return list of all elements with tag name given as an argument. It is supported in all major browsers.

<p> Para 1</p>
<p> Para 2</p>
<script>    
 var x=document.getElementsByTagName("p");
 x.length;			// return 2,			
 var p1=x[0];        //return first p element;
 var p2=x[1];        //return second p element;
</script>

Get Elements By Class Name

document.getElementsByClassName() return list of all elements with class name given as an argument. It is supported in all major browsers, except IE 8 and below doesn't support.

<p class="para"> Para 1</p>
<p class="para"> Para 2</p>
<script>    
 var x=document.getElementsByClassName("para");
 var p1=x[0];        //return first p element;
 var p2=x[1];        //return second p element;
</script>

Query Selector

document.querySelector() return first element in document with tag, id, or class name given as an argument. querySelector is pure CSS selector based. To call element by id, use "#id", to call an element with class name, use ".classname" and to call element by tagname, use "tagname". It is supported in all major browsers, except IE 7 and below. IE 8 and above support CSS 2.1, but I.E 7 doesn't support querySelector.

<p class="para" id="para1"> Para 1</p>
<p class="para" id="para2"> Para 2</p>

<script>    
var x=document.querySelector('p');            // first p tag;
var y=document.querySelector('#para1');       // id para1
var z=document.querySelector('.para');        // first para class 
var p=document.querySelector('ul li');        // first li of ul 
var q=document.querySelector('ol li');         // first li of ol 
var a=document.querySelector('p:last-child');   // last p element 
var b=document.querySelector('p:nth-child(2)'); // second p element 
</script>

Query Selector All

document.querySelectorAll() return list of elements in document with tag, id, or class name given as an argument. querySelectorAll() returns data in array-like structure. Its is pure CSS based selector. It is supported in all major browsers, except IE 7 and below. IE 8 and above support CSS 2.1, but 7 doesn't.

<p class="para"> Para 1</p>
<p class="para"> Para 2</p>
<p> Para 3</p>
<script>    
 var x=document.querySelectorAll('p');     // all p tags;
 var y=document.querySelectorAll('.para'); 
    // all elements with class para
 
 x.length         // return 3 
 y.length         // return 2 
 
 
</script>

querySelector, querySelectorAll are supported in IE 8 and above browsers. getElementsByClassName is supported in IE 9 and above browsers only.


Navigating DOM TREE

Javascript can Navigate DOM. All Node Objects have various properties and methods. All these nodes are interconnected. An element node can have children nodes, sibling nodes, parent nodes etc.

Node Property Use
childNodes return list of all children nodes connected, including text nodes.
children return only element nodes of chidren connected, excluding text nodes
firstElementChild return first child element of node
lastElementChild return last element child of a node
parentNode return parent node of a node
nextElementSibling return next adjacent element sibling of a node, will return null if node is first child.
previousElementSibling return previous adjacent element sibling of a node, will return null if node is first child.

DOM Node Properties

Node Property Use
innerHTML get text content and children nodes of element
textContent get text content of node
value get value of textbox, select, checkbox, radio buttons, textaea
checked check checked state of radio and checkbox
id get value of id attribute
classList get values of class attributes
src get source of img, audio, video, iframe.

DOM Attributes

To get value of an attribute, change attribute value and remove attribute, javaScript is having following methods.

Node Property Use
getAttribute()get attribute value, parameter should be attributes name.

document.body.getAttribute("title");                
            
setAttribute()set attributes value, two parameter required

document.body.setAttribute("title","this is body");                
            
removeAttribute() remove attribute and attributes value. one parameter required

document.body.removeAttribute("title");                
            

createElement

document.createElement is used to create a new element in dom. Any html element or custom element can be created using createElement method.

appendChild method is used to append the element created.


var ptag=document.createElement("p");    // create element
document.body.appendChild(ptag);         // append element

createElement Example


<div class="marquee"></div>
<script>
    var m=document.createElement("marquee");
    m.innerHTML="This is marquee";    
    document.querySelector(".marquee").appendChild(m); 
</script>