5,696,038 members and growing! (17,909 online)
Email Password   helpLost your password?
Web Development » HTML / CSS » HTML     Beginner License: The Code Project Open License (CPOL)

Working with HTML DOM using JavaScript

By sathesh_pandian

This is a reference article for beginners.
Javascript, HTML

Posted: 23 Jul 2008
Updated: 23 Jul 2008
Views: 7,728
Bookmarked: 8 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
4 votes for this Article.
Popularity: 1.81 Rating: 3.00 out of 5
1 vote, 25.0%
1
2 votes, 50.0%
2
0 votes, 0.0%
3
0 votes, 0.0%
4
1 vote, 25.0%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Document Object Model(Dom)

As Wikipedia says The Document Object Model (DOM) is a platform- and language-independent standard object model for representing HTML or XML and related formats. A web browser is not obliged to use DOM in order to render an HTML document. However, the DOM is required by JavaScript scripts that wish to inspect or modify a web page dynamically. In other words, the Document Object Model is the way JavaScript sees its containing HTML page and browser state.

The levels of DOM

The levels of DOM are similar like the XML hierarchy. It’s like

dom.jpg

Tricks of using JavaScript with Dom:

If you are going to use JavaScript for html Dom, you should know the Dom properties of each element which is required for creating the elements in the page. Please refer this link for html elements and their properties.

http://www.w3.org/TR/REC-DOM-Level-1/level-one-html.html#ID-882764350

For creating the elements, you can use Dom to create an element otherwise you can inject your code in the innerHTML in the block element level. If your code is not well formed, the debugger would give error so please try to use Dom for this purpose.

For creating an html element:

For DIV:

var el = document.createElement('div');
el.id="sample";
el.style.backgroundColor="#111FFF"; 
el.style.width="120px" ;
el.style.height="120px";
document.appendChild(el);  

For horizontal rule:

var el = document.createElement(hr);
el.id="sample";
//el.style.backgroundColor="#111FFF";
el.style.width="120px" ;
//el.style.height="120px";
document.appendChild(el);

if the commented codes got enabled , then the horizondal rule would look like a div element.

For Select or Dropdown box:

var el = document.createElement('div');
el.id="sample";
el.style.backgroundColor="#111FFF"; 
el.style.width="120px" ;
el.style.height="120px";
document.appendChild(el);

For adding new items or option items in the select element or in a dropdown box

optionItem = new option(text, value, defaultSelected, selected)
Or 

Var opt = document.createElement(‘option’);
Opt.value=value;
Opt.text=text;
select.options.add(opt, index);

For Table:

var tbl = document.createElement('table'); 
or
var tbl=document.getElementById(‘elementId’);

if the table is already there, the following line will retrieve the number of rows. Otherwise it will set the number of rows as 0.

var lastRow = tbl.rows.length;
insertRow is used to create a row.
var row = tbl.insertRow(lastRow);
insertcell is used to create a cell.
var cellLeft = row.insertCell(0);

from this logic you can create table dynamically.

var  totalRows='1';
//In here you have to give the required number of rows.

var totalCols='2';
//In here you have to give the required number of columns.

var intRow;
var intCol;
   for(intRow=0;intRow<totalRows;intRow++)
   {
       var row = tbl.insertRow(intRow);
       for(intCol=0;intCol<totalCols;intCol++)
       {
      var cellLeft = row.insertCell(intCol);
       }
   }

For TextArea:

var sample=document.getElementById('sample');
var el = document.createElement('textarea');
el.id="sample";
el.rows=20; //Number of rows
el.cols=20; //Number of columns
el.style.backgroundColor="#FFFFFF";
el.style.width="120px" ;
el.style.height="120px";
sample.appendChild(el);

For Input Element (textbox,fileupload,Button(submit,reset and normal button):

var sample=document.getElementById('sample');
var el = document.createElement('input');
el.id="sample";
For input text field:
el.type="text";
For input text password field:
el.type="password";
For input browse file element:
el.type="file";
For submit element:
el.type="submit";
For reset element: 
el.type="reset"; 
For hidden html element:
el.type="hidden";
For checkbox and radio button:
el.type="radio"; or el.type="checkbox";
el.checked=true;
For image: 
el.type="image"; 
el.src=””; or el.href=””;

For TextNode:

var textNode = document.createTextNode('hi');
document.appendChild(textNode);

This textnodes will be used to add text dynamically.

For Document Fragment and TextNode:

//Courtesy: From Codeproject User CCMint

<script type="text/javascript">
  function AddText(node, text){
    var tnode = document.createTextNode(text);
    node.appendChild(tnode);
    return node;
  }
  function Create(node, type){
    node.type = type;
    node.value = type;
    return node;
  }    
window.onload = function(e){
    //append a label, textbox, button and hr elements to each div on this page.
            
  //create div tags.
  var divFrag = document.createDocumentFragment();
  for(var i=0; i<200; i++){
    divFrag.appendChild(document.createElement('div'));
  }
            
  //add them to the page.
  document.body.appendChild(divFrag);
 
  //get divs.
  var divs = document.getElementsByTagName('div');
  
  //elements.
  var elements = [AddText(document.createElement('b'), 'Enter name: '),
    Create(document.createElement('input'), 'textbox'),
    Create(document.createElement('input'), 'button'),
    document.createElement('hr')];
            
  //add array of elements to a document fragment.
  var frag = document.createDocumentFragment();     
  for(var i=0; i<elements.length;>    frag.appendChild(elements[i]);
  }         
            
  //add fragment to each div.
  for(var i=0;i<divs.length;i++){>
    divs[i].appendChild(frag.cloneNode(true));
  }   
}

</script>

In the html Dom, we can create new elements and we can do the validations also. if we know the client id of the element ,then we can change attributes of the element even if it is in a master page or in a nested page. For attaching the events, we can use the following code snippet.

var el=Iframe1.document.getElementById("button1");
if (el.addEventListener){
  el.addEventListener('onclick', sample, false);
} 
else if (el.attachEvent)
{
  el.attachEvent('onclick', sample);
}

My special Thanks to CCmint.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

sathesh_pandian


have been working in dotnet technologies for the last 4 years.
Occupation: Team Leader
Company: Zylog systems pvt limited
Location: India India

Other popular HTML / CSS articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 6 of 6 (Total in Forum: 6) (Refresh)FirstPrevNext
GeneralPerformance and formattingmemberJcmorin3:41 23 Jul '08  
GeneralRe: Performance and formattingmembersathesh_pandian4:23 23 Jul '08  
GeneralRe: Performance and formattingmemberCCMint8:09 23 Jul '08  
GeneralRe: Performance and formattingmembersathesh_pandian21:38 23 Jul '08  
GeneralRe: Performance and formattingmemberCCMint5:51 24 Jul '08  
GeneralRe: Performance and formattingmembersathesh_pandian21:17 24 Jul '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 23 Jul 2008
Editor: Smitha Vijayan
Copyright 2008 by sathesh_pandian
Everything else Copyright © CodeProject, 1999-2008
Web07 | Advertise on the Code Project