Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Range or DocumentFragment to string

Is there a way to get the html string of a JavaScript Range Object in W3C compliant browsers?

For example, let us say the user selects the following: Hello <b>World</b>
It is possible to get "Hello World" as a string using the Range.toString() method. (In Firefox, it is also possible using the document's getSelection method.)

But I can't seem to find a way to get the inner HTML.

After some searching, I've found that the range can be converted to a DocumentFragment Object.

But DocumentFragments have no innerHTML property (at least in Firefox; have not tried Webkit or Opera).
Which seems odd to me: It would seem obvious that there should be some way to acces the selected items.

I realize that I can create a documentFragment, append the document fragment to another element, and then get the innerHTML of that element.
But that method will auto close any open tags within the area I select.
Besides that there surely is an obvious "better way" than attaching it to the dom just to get it as a string.

So, how to get the string of the html of a Range or DocFrag?

like image 586
SamGoody Avatar asked Feb 04 '11 10:02

SamGoody


People also ask

What is DocumentFragment?

The DocumentFragment interface represents a minimal document object that has no parent. It is used as a lightweight version of Document that stores a segment of a document structure comprised of nodes just like a standard document.

What is createContextualFragment?

createContextualFragment() method returns a DocumentFragment by invoking the HTML fragment parsing algorithm or the XML fragment parsing algorithm with the start of the range (the parent of the selected node) as the context node.

What is fragmentation in Javascript?

DocumentFragment s are DOM Node objects which are never part of the main DOM tree. The usual use case is to create the document fragment, append elements to the document fragment and then append the document fragment to the DOM tree. In the DOM tree, the document fragment is replaced by all its children.

How do I use HTML fragments?

To create a new HTML Fragment:Click on the New HTML Fragment button at the top of the screen. In the Description box enter something descriptive so that you know what the HTML code is for or what it does. This is just for your reference and will not appear on your site. Paste your HTML code into the large HTML Code ...


1 Answers

FWIW, the jQuery way:

$('<div>').append(fragment).html() 
like image 120
Brian M. Hunt Avatar answered Sep 19 '22 16:09

Brian M. Hunt