Problems while working with elements (Nodes) in DOM (JavaScript) Dynamically.

Issue 1: setAttribute doesn't work for all elements in IE (but it works fine in Mozilla and Chrome)


var tableElement = document.createElement('table');
tableElement.setAttribute("id","tableID");
tableElement.setAttribute("name","tableName");
tableElement.setAttribute("className","CSSClasName");

Cross browser Solution for the above problem is use like below

var tableElement = document.createElement('table');
tableElement.id="tableId";
tableElement.name="tableName";
tableElement.className="CSSClassName";


Issue 2: calling onClick event(Javascript Functions) on elements created using createElement (dynamic DOM)


var upArrowButton=document.createElement("input");
upArrowButton.type="button";
upArrowButton.value="\u2191";
upArrowButton.onclick="moveElementUp();";

Above statements will call moveElementUp() method on onClick() Event in Mozilla and Chrome but it doesn't work in IE. To make it work across all the browsers use like below (anonymous function)

upArrowButton.onclick=function(){ moveElementUp(); };

Issue 3: removeChild() method need to call in reverse order to properly remove multiple element from parent Node


var textareaArray= document.getElementById('parentID').getElementsByTagName('textarea');
for(var x=0;x<hildren.length;x++){
document.getElementById('parentID').removeChild(textAreaArray[x])
}

Above statements may not work properly to remove text area child nodes of the "parentID",  while removing the remove always remove the last child first . Following for do the job

for(var x=textareaArray.length-1;x>=0;x--){
document.getElementById('parentID').removeChild(textAreaArray[x])
}


Issue 4: Issue while retrieving child nodes with document.getElementsByTagName method

var children = document.getElementById('parentID').getElementsByTagName('*');

"children" array in above statement will be all decedents of "parentID" not only direct childrens. To get the direct children use the following statement

var children = document.getElementById('parentID').childNodes; //this will return only direct decedents

No comments:

Post a Comment