JavaScript DOM

document object modal
JavaScript Document Object Model ( DOM )

Document Object Model or DOM is a Tree Like Structure of HTML Document, with connected nodes, as shown above. 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 child node of html tag.


 <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
 x.nodeType		// return 1
 

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

document.body is node object. But document.images is array-like object. To excess 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 element of class para
 var p=document.querySelector('ul li');        // first li of ul element
 var q=document.querySelector('ol li');        // first li of ol element
 var a=document.querySelector('p:last-child'); // last 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 DOM
A DOM Tree for HTML Element

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
firstChild return first Child of a node
lastChild return last Child of a node
parentNode return parent node of a node
nextSibling return next adjacent sibling of a node, will return null if node is last child.
previousSibling return previous adjacent sibling of a node, will return null if node is first child.
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.

innerHTML

innerHTML property is used to get or update inner HTML of DOM. innerHTML is used only on element node, not nodelist.

Get InnerHTML

<h1>Heading <small>1</small></h1>
<p>This is a <b>para</b>.</p>
<script>
    var h1=document.querySelector("h1").innerHTML;
                    // return Heading <small>1</small>
                    
     var p1=document.querySelector("p").innerHTML;
                    // return This is a <b>para</b>.                
</script>

Set InnerHTML

<h1>Heading <small>1</small></h1>
<p>This is a <b>para</b>.</p>
<script>
    document.querySelector("h1").innerHTML="Heading <small>1</small>"

                    
     document.querySelector("p").innerHTML="This is a <b>para</b>."
            
</script>

textContent

textContent property is used to get or set text content of element. This will return plain text node onle, not children elements.

Get textContent

<h1>Heading <small>1</small></h1>
<p>This is a <b>para</b>.</p>
<script>
    var h1=document.querySelector("h1").innerHTML;
                    // return Heading 1
                    
     var p1=document.querySelector("p").innerHTML;
                    // return This is a para.                
</script>

Set textContent

Heading 1

This is a para.

<script>
    document.querySelector("h1").textContent="Heading";
                    
    document.querySelector("p").textContent="This is a para.";              
</script>

textContent property is not supported in Internet Explorer 8, use innerText for old IE.


value

value or .value returns value of an input, checkbox, select, textarea and button element.


    <input type="text" value="javascript dom">    
    
<script>
var x=document.querySelector("input").value;    
                                     // value of textbox
      
        
</script>
    

    <select>
        <option value="del">Delhi</option>
        <option val="mas">Chennai</option>
    </select>
   
<script>

var y=document.querySelector("select").value;    
                                     // value of select                                 
      
        
</script>
    

   
<button value="btn">Button 1</button>
    
<script>                                
var x=document.querySelector("button").value;    
                                     // value of button, i.e btn        
        
</script>