Search code examples
javascriptjsondocumentfragment

documentFragment converting to JSON format


Can you please help me to convert documentFragment object to JSON format? I need it to send documentFragment in message to iframe. This is my code:

  var range = window.getSelection().getRangeAt(0);
  var fragment = range.cloneContents(); 
 console.log(JSON.stringify(fragment));

But it is not working (outputs empty object {} ).


Solution

  • JSON is for data objects, not document fragments.

    You probably want the HTML string instead:

    var range = window.getSelection().getRangeAt(0);
    var fragment = range.cloneContents();
    
    // convert to html by appending the fragment to a DOM element and then read the element's innerHTML:
    var div = document.createElement('div');
    div.appendChild(fragment);
    console.log(div.innerHTML);