How do I wrap a text selection from window.getSelection().getRangeAt(0) with an html tag?

前端 未结 3 1069
忘掉有多难
忘掉有多难 2020-11-30 14:14

How do I take a selection from window.getSelection().getRangeAt(0) and surround it with an HTML tag such as \'span\' or \'mark\'? I prefer a straight javascript or jQuery so

3条回答
  •  醉酒成梦
    2020-11-30 14:52

    If the selected text is all contained within a single text node, you can use the surroundContents() method of the Range. However, that doesn't work in the general case. The thing to do is surround each text node within the Range in a . My Rangy library has a module that does this and works cross-browser (IE <= 8 does not natively support DOM Range).

    Example code using Rangy:

    
    
    

提交回复
热议问题