cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
Showing results for 
Search instead for 
Did you mean: 

Community Tip - Need help navigating or using the PTC Community? Contact the community team. X

attaching a Range to an empty DocumentFragment in Javascript

jsulak
1-Visitor

attaching a Range to an empty DocumentFragment in Javascript

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 3

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
jsulak
1-Visitor
(To:jsulak)

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
jsulak
1-Visitor
(To:jsulak)

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
Announcements

Top Tags