I would like to parse my rich text editor contents into a JSON format. This would be simple if I could use something like querySelectorAll but I cannot seem to find a way to convert the value from the editor into a DOM node.
Calling on domparser returns error:
"Failed to execute 'postMessage' on 'Window': DocumentFragment object could not be cloned."
1 Like
Hey @Gregorio,
If I understood correctly, there are two issues:
- Converting the HTML output of a RichText component into JSON
- Render the HTML output on the page
The HTML output of the Rich Text component can be accessed via value
. You could use this to render the content anywhere you like. Meaning, you don't have to write a parser/renderer.
Not sure if I understood the JSON ask correctly. Do you want to convert the editor output into JSON? If so, you would need to build that in with something like this.
Hope that helps
Thanks. Your linked solution for converting HTML to JSON is what I am looking for.
However inside Retool JS code I am not having luck accessing DOMParser.
Strange, works fine for me.
Can you try this snippet in a new JS Query:
var initElement = richTextEditor1.value;
var json = mapDOM(initElement, true);
console.log(json);
return json;
function mapDOM(element, json) {
var treeObject = {};
// If string convert to document Node
if (typeof element === "string") {
if (window.DOMParser) {
parser = new DOMParser();
docNode = parser.parseFromString(element, "text/xml");
} // Microsoft strikes again
else {
docNode = new ActiveXObject("Microsoft.XMLDOM");
docNode.async = false;
docNode.loadXML(element);
}
element = docNode.firstChild;
}
//Recursively loop through DOM elements and assign properties to object
function treeHTML(element, object) {
object["type"] = element.nodeName;
var nodeList = element.childNodes;
if (nodeList != null) {
if (nodeList.length) {
object["content"] = [];
for (var i = 0; i < nodeList.length; i++) {
if (nodeList[i].nodeType == 3) {
object["content"].push(nodeList[i].nodeValue);
} else {
object["content"].push({});
treeHTML(
nodeList[i],
object["content"][object["content"].length - 1]
);
}
}
}
}
if (element.attributes != null) {
if (element.attributes.length) {
object["attributes"] = {};
for (var i = 0; i < element.attributes.length; i++) {
object["attributes"][element.attributes[i].nodeName] =
element.attributes[i].nodeValue;
}
}
}
}
treeHTML(element, treeObject);
return json ? JSON.stringify(treeObject) : treeObject;
}
1 Like
Thanks. I had something similar and got errors. I'm sure I was misusing domparser.
1 Like