views:

6178

answers:

2

Hi guys,

I have a problem where I need to insert a text (string, may or may not have html tags) to a div. It has to be a div and not a textarea.

Is there anyway to do that? First of all, I need to get the cursor position, then inserting the text in that position.

It's similar to function insertAdjacentText, but it can only insert before or after a tag, and only works in IE.

Refer to this URL: http://yart.com.au/test/iframe.aspx. Note how you can position the cursor in the div, we need to add text at the cursor location.

+5  A: 

The Range and Selection Objects

Use the selection and range objects. These contain all kinds of information about the current selection, and where it lies within the node tree.

Fair Warning: It's not entirely impossible to do what you're describing, but if you get very fancy, you'll be in pretty deep water of browser quirks and incompatibilities. You're going to have to do a lot of object detection, checking to make sure you've got consistent values and methods. Incrementally check all of your browsers as you develop. Good luck!

keparo
+5  A: 

If all you need to do is insert HTML at the current selection / insertion point, that is doable. Off the top of my head (to get you started):

In IE, use document.selection.createRange().pasteHTML(theNewHTML).

In other browsers, you should be able to use document.execCommand("InsertHTML", ...).

I've used these kinds of techniques only in editable iframes/documents, not divs, but these calls should work if the div is focused, I believe.

As another answer warned, it gets ugly if you want finer-grained control, like inserting text in other places.