Sevenforge Sevenforge by Curtis Spencer home

Building a DOM from a String in Javascript

January 12, 2010

Sometimes you have a HTML or XML string and want to turn it into a DOM object so you can run methods like getElementById on it. Here is a reasonable way to make a DOM object that is cross browser as far as I know.

if (window.DOMParser) {
  parser=new DOMParser();
  xmlDoc=parser.parseFromString(text,"text/xml");
} else {
  // Internet Explorer
  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async="false";
  xmlDoc.loadXML(text);
}

Fork me on GitHub