Search code examples
javascriptwebkit

How do I select arbitrary text on the page using javascript?


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.


Solution

  • 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: 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.