Search code examples
javascriptcontenteditablerange

Highlight/select multiple divs with ranges w/ contenteditable?


Let's say I have a set of contenteditable="true" divs.

<div id="0" contenteditable="true"></div>
<div id="1" contenteditable..></div>
<div...etc></div>

I can't have one div, multiple divs is a must. How could I highlight the content of more than one div? Using ranges? Anything else?


Solution

  • The answer is that it depends on the browser. See this example for a test of two methods using Ranges. The first attempts to create a Range per editable <div> and add all of them to the selection. The second attempts to create a single Range encompassing the contents of two editable <div>s.

    Results:

    • In all browsers, it is impossible for the user to create a selection that lives in more than one editable element;
    • Firefox is the most permissive of the major browsers. Both programmatic methods work.
    • Safari and Chrome is the least permissive: neither method selects content from more than one editable element.
    • Opera 11 does not support multiple Ranges in the selection, but does support a selected Range spanning more than one editable element.
    • IE pre-version 9 does not support DOM Range or the same Selection API as other browsers, but the equivalent TextRange code does not allow selection from more than one editable element.