javascriptjqueryselection

window.getSelection() offset with HTML tags?


If I have the following HTML:

<div class="content">
Vivamus <span>luctus</span> urna sed urna ultricies ac tempor dui sagittis.
</div>

And I run an event on mouseup that sees the ranges of the selected text:

$(".content").on("mouseup", function () {
    var start = window.getSelection().baseOffset;
    var end = window.getSelection().focusOffset;
    if (start < end) {
        var start = window.getSelection().baseOffset;
        var end = window.getSelection().focusOffset;
    } else {
        var start = window.getSelection().focusOffset;
        var end = window.getSelection().baseOffset;
    }
    console.log(window.getSelection());
    console.log(start + ", " + end);
});

And I select the word Vivamus from the content, it will log 1, 8, as that is the range of the selection.

If, however, I select the word urna, it will log 15, 20, but won't take into account the <span> elements of the HTML.

Is there anyway for focusOffset and baseOffset to also count for HTML tags, instead of just the text?


Solution

  • Update

    Live Example: http://jsfiddle.net/FLwxj/61/

    Using a clearSelection() function and a replace approach, I was able to achieve the desired result.

    var txt = $('#Text').html();
    $('#Text').html(
        txt.replace(/<\/span>(?:\s)*<span class="highlight">/g, '')
    );
    clearSelection();
    

    Sources:


    Below you'll find some working solutions to your problem. I placed them in order of code efficiency.

    Working Solutions

    Other helpful solutions: