domJSON
domJSON copied to clipboard
[question] How to pass pure html in toJSON() method?
I work on code editor and have following question:
DomJson Accepts html element as an argument for domJSON.toJSON(element)
Can i pass pure html string instead? domJSON.toJSON('<p>some code</p>')
i tried that and it logs error length is undefined
which may be because it expects html element, not a string.
Sorry for the late reply. You are correct, it expects an HTML element. I'll look into adding support for strings, but under the hood all that would do is create new element, append the string as innerHTML, and then parse the resulting HTML element. In the meantime, you could probably just use the following code to achieve the same result:
var myHTMLString = '<p>some code</p><p>Uh-oh, a second node!</p>'; //Or whatever HTML
var div = document.createElement('div');
div.innerHTML = myHTMLString;
var frag = document.createDocumentFragment();
//Iterate over the nodes added to the div, and move them over to the fragment
Array.prototype.forEach.call(childNodes, function(node) {
frag.appendChild(node);
});
//Pass the populated fragment to domJSON
domJSON.toJSON(frag);
Thank you for the response and code example, i think adding support for pure string along with htmlElement is a good idea, just for different use cases.