Tuesday, June 02, 2009

Cross Browser Compatible Javascript DOMelement function

In the past... you had to do
//------------
var a = document.createElement('div');
a.setAttribute('class','myclass');
a.setAttribute('id','id_mydiv');
document.getElementById('otherdiv').appendChild(a);

//------------
to create a dom element... and it only worked in firefox. to get one that works in internet explorer you have to do:
//------------
var a;
try {
  a = document.createElement('<div class=myclass id=id_mydiv>');
}
catch(e) {
  a = document.createElement('div');
  a.setAttribute('class','myclass');
  a.setAttribute('id','id_mydiv');
}
document.getElementById('otherdiv').appendChild(a);

//------------
include the function below, and it will work in both browsers:
//------------
var a = DOMelement('div','class':'myclass','id':'id_mydiv');
document.getElementById('otherdiv').appendChild(a);

//------------

function DOMelement(elementname,attributes)
{
  var htmlspecial = function(tmp_str){
    var histogram = {"&":"&amp;","'":"&#39;", "\"":"&#34;","<":"&lt;",">":"&gt;"};
    for (symbol in histogram)
      tmp_str = tmp_str.split(symbol).join(histogram[symbol]);
    return tmp_str;
  }
  var element;
  try{
    var attribute_str = '';
    for(attribute_name in attributes)
      if (attribute_name!='text')
        attribute_str+= attribute_name+"='"+htmlspecial(o.attributes[attribute_name])+"'";
    element = document.createElement("<"+elementname+" "+attribute_str + ">");//IE
  }catch (e){
    element = document.createElement( elementname );
    for(attribute_name in attributes)
      if (attribute_name!='text')
        element.setAttribute( attribute_name , attributes[attribute_name] );
  }
  if (attributes && attributes['text'])
    element.innerHTML = attributes['text'];
  return element;
}

No comments: