Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
30
rated 0 times [  36] [ 6]  / answers: 1 / hits: 26796  / 14 Years ago, fri, february 4, 2011, 12:00:00

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?


More From » selection

 Answers
3

No, that is the only way of doing it. The DOM Level 2 specs from around 10 years ago had almost nothing in terms of serializing and deserializing nodes to and from HTML text, so you're forced to rely on extensions like innerHTML.



Regarding your comment that




But that method will auto close any
open tags within the area I select.




... how else could it work? The DOM is made up of nodes arranged in a tree. Copying content from the DOM can only create another tree of nodes. Element nodes are delimited in HTML by a start and sometimes an end tag. An HTML representation of an element that requires an end tag must have an end tag, otherwise it is not valid HTML.


[#93907] Wednesday, February 2, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dawnc

Total Points: 612
Total Questions: 94
Total Answers: 98

Location: Sweden
Member since Fri, Apr 16, 2021
3 Years ago
;