Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 531
Lucas Avatar asked Nov 15 '09 01:11

Lucas


People also ask

How do you select text in JavaScript?

select() The HTMLInputElement. select() method selects all the text in a <textarea> element or in an <input> element that includes a text field.

When to use innerHTML?

innerHTML is useful at any time to insert new HTML tags/content as a string, and can be more easily directed to specific elements in the DOM regardless of when/where the JavaScript is run.

How to insert innerHTML?

To append using the innerHTML attribute, first select the element (div) where you want to append the code. Then, add the code enclosed as strings using the += operator on innerHTML.


1 Answers

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.

like image 180
Lucas Avatar answered Oct 05 '22 22:10

Lucas