0

I've been trying to select only the last chars of a ContentEditable Element

I've used an example from Mozilla on http://jsfiddle.net/mh7HK/ which works on an input field but not on a ContentEditable field, although, selecting all does work

This works:

var elem = document.getElementById("contentEdit");
var range = document.createRange();
range.selectNodeContents(elem);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);

This doesn't:

var elem = document.getElementById("contentEdit");
var range = document.createRange();
range.setStart(elem, 5) // breaks range Object?
range.setEnd(elem, 8)   // breaks range Object?
range.selectNodeContents(elem);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);

The .setStart() and .setEnd() should work like that, right?

I've looked at the limited Documentation of jQuery carrot, jQuery selection, Rangy etc., but they all seem to be aimed at getting the selection not setting it.

Tim Down
  • 318,141
  • 75
  • 454
  • 536
TrySpace
  • 2,233
  • 8
  • 35
  • 62

1 Answers1

0

Two problems:

  1. selectNodeContents(node) moves the range to encompass the whole content of node, so your setStart() and setEnd() calls are essentially ignored.

  2. setStart(node, offset) moves the range's start boundary to offset offset within node. In the case of element, that means placing the boundary after offset child nodes of the element. In the case of a text node, which is probably what you want, the range boundary is placed after offset characters. Same with setEnd(). If you have a single text node within your editable element, you're probably done. Once you start have nested elements, you may want a more subtle approach if you want to set the selection relative to your editable element's text content.

See also https://stackoverflow.com/a/24117242/96100.

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536