Converting Range or DocumentFragment to string

前端 未结 6 1293
无人共我
无人共我 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:41

    No, that is the only way of doing it. The DOM Level 2 specs from around 10 years ago had almost nothing in terms of serializing and deserializing nodes to and from HTML text, so you're forced to rely on extensions like innerHTML.

    Regarding your comment that

    But that method will auto close any open tags within the area I select.

    ... how else could it work? The DOM is made up of nodes arranged in a tree. Copying content from the DOM can only create another tree of nodes. Element nodes are delimited in HTML by a start and sometimes an end tag. An HTML representation of an element that requires an end tag must have an end tag, otherwise it is not valid HTML.

提交回复
热议问题