Wednesday, January 16, 2013

Creating HTML elements dynamically with JavaScript

When we are developing web pages using markup languages like HTML, the web page will be appeared as we have already written with HTML. But what if we need to add some more HTML elements, add/edit some of properties of HTML elements even after rendering to browser? JavaScript comes into the game here. Below I have given a JavaScript function to add a row for an existing HTML table with some of HTML elements inside table cells.

function addRow(tableId){
   var table = document.getElementById(tableId);
   var row = table.insertRow(rowCount);

   var cell1 = row.insertCell(0);
   var element1 = document.createElement("label");
   element1.innerHTML = "Cell One-Label";
   cell1.appendChild(element1); 

   var cell2 = row.insertCell(1);
   var element2 = document.createElement("input");
   element2.type = "text";
   element2.value - "Cell Two-Input Text";

   cell2.appendChile(element2); 
   var cell3 = row.insertCell(2);
   var element3 = document.createElement("textarea");
   element3.value = "Cell Three-Text Area";
   cell3.appendChild(element3);
}

By calling this function(using a button click event, etc.) with the 'id' of the relevant table as an argument, we can add a label, input text and a textarea there.

Also when we need to set some attributes to be set dynamically, it also can be done. Below I'm explaining this by using the element1.

element1.setAttribute('id','myLabel'); 
element1.setAttribute("onChange",someFunction());
element1.setAttribute("onkeypress",someFunction());
element1.setAttribute("style","width:65px; text-align:right");

This way, we can add almost all the attributes for an HTML element dynamically. 





No comments:

Post a Comment