1

In my app, I want the user to be able to select a bunch of text and highlight it, similar to "marker" features in word/libreoffice etc.

I got some limited success with this fragment, but it fails when selecting more complex (= block elements?) content:

let sel = document.getSelection()
let range = sel.getRangeAt(0)
let marker = document.createElement('span')
marker.className = 'highlight'
range.surroundContents(marker)
range.collapse()

So - how do I get from a selection or range to a modified HTML where every text node within is wrapped in a highlight marker? Note that I don't care too much if the structure of the selection needs to be rewritten, as long as the resulting layout stays the same.

A working sample of the above can be found here: http://jsfiddle.net/7g5nb94w/

Dave Vogt
  • 18,600
  • 7
  • 42
  • 54
  • Could you post a working example? I know it's sometimes hard but it's hard to answer it now because we don't know for sure what the pitfalls are. Is it really block vs inline elements? Is it multiple lines problem? I really don't know now. – Wimanicesir Nov 21 '18 at 16:27
  • @Wimanicesir Added a jsfiddle to play around with – Dave Vogt Nov 21 '18 at 16:42
  • Possible duplicate of [javascript contentEditable - wrap cross-tag selections](https://stackoverflow.com/questions/29633473/javascript-contenteditable-wrap-cross-tag-selections) – Dave Vogt Nov 22 '18 at 11:37
  • This question comes from a different angle, but the solution is the same: https://stackoverflow.com/questions/29633473/javascript-contenteditable-wrap-cross-tag-selections – Dave Vogt Nov 22 '18 at 11:38

0 Answers0