TheGeekZn
TheGeekZn

Reputation: 3924

Javascript `getSelection().getRangeAt(0)` not working correctly with tags

Demo: http://jsbin.com/caxuk/1/edit

I am using window.getSelection().getRangeAt(0) to select some text to manipulate. However, when I select over a <b> tag, the range returned is 1.

How would I be able to get the proper range, no matter what tags are in the way?\

Code for completeness:

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <div id="text">
    <b>smfk</b> - osdnmfoaidsmnfoids
  </div>
</body>
</html>

$("#text").mouseup(function (evt) {
  var selectionRange = window.getSelection().getRangeAt(0);
  var range = selectionRange.endOffset - selectionRange.startOffset;

    alert(range);

});

Highlighting smfk, smfk - etc returns 1, 2, 3... as ranges

EDIT: I need to return the range excluding any tags... So if I select smfk -, it should return 0-4, not 0-11

Upvotes: 1

Views: 1491

Answers (2)

TheGeekZn
TheGeekZn

Reputation: 3924

$("#text").mouseup(function (evt) {
  var selectionRange = window.getSelection().getRangeAt(0);
  var start = selectionRange.startOffset;
  var end = selectionRange.endOffset;  
  var length = window.getSelection().toString().length;

  if (start === end || end < start || (end - start) !== length){
    end = start + length;
  }

  var range = end - start;

    alert(range);

});

Just add some verifications to the calculation.
Demo: http://jsbin.com/caxuk/2/edit

Upvotes: 1

mauretto
mauretto

Reputation: 3212

endOffset refers to endContainer (unbolded text), startOffset refers to startContaner (bolded text).

Easy solution for this case: if start container is not equal to end container, start container length - startOffset + endOffset, try yourself.

Have a look at Range spec, specifically at [2.7. Extracting Content] section.

Upvotes: 0

Related Questions