0

How do I take a string and create an html fragment with it in IE. This works fine in non-ie browsers.

var str = "<div>Foo</div>";
var range = document.createRange();
var frag = range.createContextualFragment(str);
var e = document.getElementById("element");
e.appendChild(frag);
Daniel Vandersluis
  • 91,582
  • 23
  • 169
  • 153
Praesagus
  • 2,029
  • 5
  • 30
  • 48
  • `createContextualFragment` is not at all necessary considering the widespread adoption of `innerHTML`. Here are a couple answers that use document fragments to avoid the dangling extra div you'd get with a straight `innerHTML` approach: http://stackoverflow.com/questions/814564/inserting-html-elements-with-javascript/814649#814649 and http://stackoverflow.com/questions/788614/ways-to-increase-performance-when-set-big-value-to-innerhtml/788661#788661 – Crescent Fresh Jan 22 '10 at 19:56
  • 1
    innerHTML has quite a few idiosyncracies across the major browsers. I'd really like to know how to do this using w3c compliant code. – Praesagus Feb 04 '10 at 22:48

1 Answers1

1

You may want to consider using jQuery? Cross-browser compatible and far easier to use:

$(document).ready(function() {
  var str = "<div>Foo</div>";
  $('#element').append(str); //assuming your element's id is 'element'
});

jQuery site and documentation

KP.
  • 13,218
  • 3
  • 40
  • 60