Skip to main content
1-Visitor
January 20, 2011
Question

attaching a Range to an empty DocumentFragment in Javascript

  • January 20, 2011
  • 3 replies
  • 961 views
Hello Adepters,

I'm trying to convert an arbitrary string of markup into a DocumentFragment. The only method I know of to do that is insertParsedString(), with is a method on Range objects.

Unfortunately, I haven't been able to figure out how to attach a range to a fragment and make it work right. I've tried a few variations on the following theme:

var d = Application.activeDocument;
var f = d.createDocumentFragment();
var r = f.getOwnerDocument().createRange();
r.selectNodeContents(f);
r.insertParsedString("test");

Doing that, I get a "paste would make in the pasted region out of context." I've also tried using the setStart() and setEnd() methods on range to no avail.

Does anyone have any advice?

Thanks,

James

    3 replies

    18-Opal
    January 20, 2011
    Hi James--

    Try this formulation:

    var doc = Application.activeDocument;
    var frag = doc.createDocumentFragment();
    var r = frag.ownerDocument.createRange();
    r.setStart(frag,0);
    r.setEnd(frag,0);
    r.insertParsedString("bar");

    Seems to work for me.

    --Clay
    jsulak1-VisitorAuthor
    1-Visitor
    January 20, 2011
    Hmm. Thanks, Clay. I tried that before, but it turns out that it works in 5.4 but doesn't in 5.3, which was what I was originally testing in. That's annoying, but there's probably not a lot I can do about it other than upgrade.

    Thanks,

    James
    jsulak1-VisitorAuthor
    1-Visitor
    January 25, 2011
    Just to follow up...

    After further investigation, this does work in 5.3, despite the exception being thrown. So this (kludge) works:

    var doc = Application.activeDocument;
    var frag = doc.createDocumentFragment();
    var r = frag.ownerDocument.createRange();
    r.setStart(frag,0);
    r.setEnd(frag,0);
    try {
    r.insertParsedString("bar");
    } catch(e) {
    // swallow exception
    }

    -James