Click here to Skip to main content
14,973,117 members
Articles / Web Development / HTML
Article
Posted 23 Jul 2008

Tagged as

Stats

48.8K views
24 bookmarked

Working with HTML DOM using JavaScript

Rate me:
Please Sign up or sign in to vote.
3.23/5 (6 votes)
23 Jul 2008CPOL2 min read
This is a reference article for beginners

Introduction - 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 to 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 are required for creating the elements in the page. Please refer to this link for HTML elements and their properties.

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 an error so please try to use DOM for this purpose.

For Creating an HTML Element

For DIV

JavaScript
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

JavaScript
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 get enabled, then the horizontal rule would look like a div element.

For Select or Dropdown Box

JavaScript
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:

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

Or:

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

For Table

JavaScript
var tbl = document.createElement('table'); 

Or:

JavaScript
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.

JavaScript
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 a table dynamically:

JavaScript
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

JavaScript
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)

JavaScript
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

JavaScript
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

JavaScript
<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 too. 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:

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

I would like to give special thanks to CCmint.

History

  • 23rd July, 2008: Initial post

License

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

Share

About the Author

sathesh pandian
Technical Lead
India India
have been working in web technologies for the last 8 years.

Comments and Discussions

 
QuestionMy Vote of 4 Pin
Alireza_136214-Dec-12 3:07
MemberAlireza_136214-Dec-12 3:07 
GeneralQuestion about controlling DOM using Javascript Pin
jason321d1-Jun-11 11:17
Memberjason321d1-Jun-11 11:17 
Hi, Is it possible to export this functionality outside of browser.
Like i want to control the DOM, i.e send Javascript commands to the loaded webpage in real time from my external application in C++.

I have tried a lot but have not yet find any way how to accomplish this job. Even the plugin idea didn't really work. Would be great if you could give me some idea.
GeneralRe: Question about controlling DOM using Javascript Pin
sathesh pandian28-Apr-12 18:37
Membersathesh pandian28-Apr-12 18:37 
GeneralPerformance and formatting Pin
Jcmorin23-Jul-08 2:41
MemberJcmorin23-Jul-08 2:41 
GeneralRe: Performance and formatting Pin
sathesh pandian23-Jul-08 3:23
Membersathesh pandian23-Jul-08 3:23 
GeneralRe: Performance and formatting Pin
CCMint23-Jul-08 7:09
MemberCCMint23-Jul-08 7:09 
GeneralRe: Performance and formatting Pin
sathesh pandian23-Jul-08 20:38
Membersathesh pandian23-Jul-08 20:38 
GeneralRe: Performance and formatting Pin
CCMint24-Jul-08 4:51
MemberCCMint24-Jul-08 4:51 
GeneralRe: Performance and formatting Pin
sathesh pandian24-Jul-08 20:17
Membersathesh pandian24-Jul-08 20:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.