Saturday 1 December 2012

Creation of Dynamic HTML tags using DOM


We can generate almost all tags of HTML through Javascript dynamically.

Example:
This is the piece of code in which I am generating a table, in that table there would be rows and columns. In those columns, I will generate a text box in one column and write a label in another.

<apex:Page>
<script type="text/javascript">

// call this function from any action it will create a table with text box and its label.
Function createTags(){
var newTable = document.createElement('table'); // Instance of table tag is created
newTable.id ='newTable'; //sets id
newTable.width = '100%'; // sets width attribute

var tbdy =document.createElement('TBODY'); // create instance of Body of table.
                newTable.appendChild(tbdy); // adds child elements of table

var newTableRow = document.createElement('tr'); //row created              
                tbdy.appendChild(newTableRow); // added as child in tbody

var newTableColumnForTextBoxLabel = document.createElement('td'); // column created.
newTableColumnForTextBoxLabel.innerHTML = 'New TextBox: '; // this inner HTML will work as label.
newTableRow.appendChild(newTableColumnForTextBoxLabel); // added as child.

var newTableColumnForTextBox = document.createElement('td'); // column created.
newTableRow.appendChild(newTableColumnForTextBox);  // added as child.

var newTextBox =document.createElement('input'); // input tag created, default is of Type text.
newTableColumnForTextBox.appendChild(newTextBox); // added as child
}
</script>
</apex:Page>

Note:-

1. createElement()- to create the element.
appendChild()- to append any element as a child of any element.
removeChild()- to remove the child element of any element.

/*** element = document.getElementById("element-id");
element.parentNode.removeChild(element);  // in case if dont know the parent element
**/

2. addEventListener('event_Name',listener,state)- to add action on dynamically created elements, it doesnt work in IE.
attachEvent('event_Name',listener)- to add action on dynamically created elements, it works in IE.

listener- This must be an object implementing the EventListener interface, or simply a JavaScript function.
state- As to the true or false that is the last argument of addEventListener, it is meant to state whether the event handler should be executed in the capturing or in the bubbling phase. If you’re not certain whether you want capturing or bubbling, use false (bubbling).

3. innerHTMl(element)- it contains all of the element's descendants.

4. we can also set inline style attribute through this.
e.g: newTextBox.style.visibility ='hidden';

5. insertBefore()- it inserts the node exactly before the given node.

e.g: node.insertBefore(newnode, existingchild);
It inserts newnode as a child of node and exactly before the existingchild.

6. we can add multiple child in a elements, the order of display would be same as adding.


No comments:

Post a Comment