javascriptfirefox

Is there a way to edit a Range without discarding other existing Ranges?


I am attempting to perform operations on multiple text selections by using a loop, that runs after pressing a button.

Because each iteration of the loop makes changes to the highlighted nodes, I need to alter each Range's start and end point accordingly.

The issue is: accessing the Range.setStart and Range.setEnd methods, whilst multiple selections exist seems to discard all Ranges - i.e. all text gets deselected. Furthermore, the Selection.type property gets changed from "Range" to "Caret". None of this happens if only one selection is made.

Am I doing something wrong, or is this a bug?

I've spend a considerable amount of time on trying to avoid this issue, but to no avail. I would greatly appreciate an expertly voice on the topic.

And just for clarity: I am using a Firefox-based browser. I making multiple selections by holding down CTRL, whilst click-dragging the cursor. I access the resulting Ranges with the following code:

const selection = window.getSelection()
const range = selection.getRangeAt(index)

Solution

  • Try this experiment below:

    1. Double-click on bbbbb
    2. Ctrl+Double-click on fffff
    3. Ctrl+Double-clidk on hhhhh
    4. Click on test

    function clicked() {
        const container = document.querySelector(".container");
        const selection = window.getSelection();
        selection.getRangeAt(0).setStart(container.children[0], 0);
    }
    <div class="container">
    <span>aaaaa</span>
    <span>bbbbb</span>
    <span>ccccc</span>
    <span>ddddd</span>
    <span>eeeee</span>
    <span>fffff</span>
    <span>ggggg</span>
    <span>hhhhh</span>
    <span>iiiii</span>
    <span>jjjjj</span>
    <span>kkkkk</span>
    <span>lllll</span>
    <span>mmmmm</span>
    <span>nnnnn</span>
    <span>ooooo</span>
    <span>ppppp</span>
    <span>qqqqq</span>
    <span>rrrrr</span>
    <span>sssss</span>
    <span>ttttt</span>
    </div>
    <input type="button" onclick="clicked()" value="test">

    What happens for me: changes the start of the first select to extend it to the start of aaaaa while the other selections are left unchanged.

    What do I expect: the same.

    So, if it did not work for you, I can imagine that there are multiple selections in your case and you extend one and unwillingly absorb the others. But only you can confirm or deny this. Nevertheless, the feature works for me.