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
So, how to get the string of the html of a Range or DocFrag?
Contrary to the other responses, it is possible to directly turn a DocumentFragment
object into a DOMString
using the XMLSerializer.prototype.serializeToString
method described at https://w3c.github.io/DOM-Parsing/#the-xmlserializer-interface.
To get the DOMString
of a Range
object, simply convert it to a DocumentFragment
using either of the Range.prototype.cloneContents
or Range.prototype.extractContents
methods and then follow the procedure for a DocumentFragment
object.
I've attached a demo, but the gist of it is in these two lines:
const serializer = new XMLSerializer();
const document_fragment_string = serializer.serializeToString(document_fragment);
(() => {
"use strict";
const HTML_namespace = "http://www.w3.org/1999/xhtml";
document.addEventListener("DOMContentLoaded", () => {
/* Create Hypothetical User Range: */
const selection = document.defaultView.getSelection();
const user_range_paragraph = document.getElementById("paragraph");
const user_range = document.createRange();
user_range.setStart(user_range_paragraph.firstChild, 0);
user_range.setEnd(user_range_paragraph.lastChild, user_range_paragraph.lastChild.length || user_range_paragraph.lastChild.childNodes.length);
selection.addRange(user_range);
/* Clone Hypothetical User Range: */
user_range.setStart(selection.anchorNode, selection.anchorOffset);
user_range.setEnd(selection.focusNode, selection.focusOffset);
const document_fragment = user_range.cloneContents();
/* Serialize the User Range to a String: */
const serializer = new XMLSerializer();
const document_fragment_string = serializer.serializeToString(document_fragment);
/* Output the Serialized User Range: */
const output_paragraph = document.createElementNS(HTML_namespace, "p");
const output_paragraph_code = document.createElementNS(HTML_namespace, "code");
output_paragraph_code.append(document_fragment_string);
output_paragraph.append(output_paragraph_code);
document.body.append(output_paragraph);
}, { "once": true });
})();
Hello World