Gal
Gal

Reputation: 5416

HTML - How to get selection offsets with relatives to HTML tags

Suppose my HTML looks something like this

<div>
    <p> start<span>span</span>end </p>
</div>

I need to be be able to get the offsets when a selection is made, without ignoring the span tags.

e.g. suppose to user selected

t<span>span</span>e

I want the to get 4 as starting offset and 24 as the ending offset. The selection object obtained via window.getSelection() returns 1,8, which is rather useless to me. I obviously need to handle all cases where the user selects only the inner span, or part of the span etc.

Thanks

Upvotes: 0

Views: 554

Answers (1)

Gal
Gal

Reputation: 5416

I've ended up solving it thusly:

            var range = sel.getRangeAt(0);
            // inserts two spans at the beginning and end of the range, to
            // calculate the offsets
            var div = document.createElement("span");
            div.setAttribute("class", START_NODE);
            range.insertNode(div);
            range.collapse(false);
            div = document.createElement("span");
            div.setAttribute("class", END_NODE);
            range.insertNode(div);
            // gets the offsets by looking up the location of the inserted spans
            // removes them after finding the offsets (also so the starting
            // offset won't screw up the ending offset)
            comment.startOffset = p.html().indexOf('<span class="' + START_NODE + '">');
            $("." + START_NODE).remove();
            comment.endOffset = p.html().indexOf('<span class="' + END_NODE + '">');
            $("." + END_NODE).remove();
            p.html(p.html());

basically, I've added a SPAN at the beginning of the range selection, then collapsed the range and added a SPAN at the end of it. Then I simply searched for the index of the first span I've added, and the index of the second span I've added to find the offsets.

Upvotes: 1

Related Questions