Converting Range or DocumentFragment to string

前端 未结 6 1141
无人共我
无人共我 2021-02-05 03:07

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

6条回答
  •  无人及你
    2021-02-05 03:43

    Another way to do it would be to iterate over childNodes:

    Array.prototype.reduce.call(
        documentFragment.childNodes, 
        (result, node) => result + (node.outerHTML || node.nodeValue),
        ''
    );
    

    Wouldn't work for inlined SVG, but something could be done to get it to work. It also helps if you need to dome some chained manipulation with the nodes and get an html string as a result.

提交回复
热议问题