views:

164

answers:

3

Let's say I have a contentEditable div, to the user can edit and change the text and elements inside it. How do I arbitrarily change the selection in this div with javascript? By "change" I don't mean "change the contents of whatever the user has selected", I mean actually change what is selected. The user should then be able to type over the selection, replacing it with something else.

This should take into account that I may want to select text across elements. For instance:

<p>Some text <span>goes</span> here.</p>

I may for instance want to select "Some text go", or everything inside the <p>.

This only needs to work in Safari/Webkit.

Thanks in advance. As a native code developer, I find the DOM and Javascript in general quite frustrating.

+1  A: 

You can use document.getElementById('your_text_id').setSelectionRange(start, end); and you can use Math.random() to generate random numbers for start and end

Soufiane Hassou
Thanks, but I need to be able to select across element boundaries too. And by "arbitrary", I didn't mean *random*. I know exactly the elements where the selection should start and end, down to the character offset.
Lucas
+1  A: 

Unless you need to write your own, you may want to look at tinyMCE, http://tinymce.moxiecode.com/, as it is a nice WYSIWYG editor in javascript.

In order to do this you will probably want to look at something like this: http://codingtricks.blogspot.com/2009/03/javascript-select-partial-text-in-div.html

These may also be helpful: http://stackoverflow.com/questions/1426815/javascript-ranging-gone-wrong https://developer.mozilla.org/en/DOM/window.getSelection

What you are trying to do will be complex, as you will need to take the selected area, remove all the tags, then put in the tag that you want for the selected area.

James Black
A: 

Just to answer my own question in detail so anyone searching for something similar doesn't have to go looking elsewhere...

The code I ended up using was something like this:

var range = document.createRange();
range.setStart( <get the node the selection starts in>, <char offset in that node> );
range.setEnd( <get the node the selection ends in>, <char offset in that node> ); 

window.getSelection().removeAllRanges();
window.getSelection().addRange(range);

Big thanks to James Black for pointing me in the right direction.

Lucas