window.getSelection() gives me the selected text, but I want the HTML

后端 未结 3 1273
逝去的感伤
逝去的感伤 2020-11-28 22:18

I\'m extending a WYSIWYG HTML editor (for Firefox), I want to add tags around a selection. I can\'t find a function to accomplish this in the Mozilla Midas specification.

3条回答
  •  孤城傲影
    2020-11-28 23:14

    Tim Down's answer is on the right track. However one issue is that extractContents() will remove the selection from the dom. You can use

    window.getSelection().getRangeAt(0).cloneContents(); 
    

    to just get a copy of what's selected. You could then wrap that with your new tag and then replace the selection with it. Tim Down's concern about the range spanning multiple HTML elements is certainly a valid one. I think once you get the range, it 'fixes' up the html, but when you put it back in it could cause problems. Here's a good resource on the Range object.

提交回复
热议问题