Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add / insert / update text inside contenteditable div at a particular position?

The HTML code looks like this

<div id="txtarea" contenteditable="true">Some text</div>

I have to insert some new text based on some event at a particular position in the above div. The event calls the function say updateDiv(txt, positon). For example it says
updateDiv("more ",5);

So the div should become be

<div id="txtarea" contenteditable="true">Some more text</div>

I tried a lot of javascript and jquery but nothing seem to work.

like image 292
MeetM Avatar asked Apr 25 '12 12:04

MeetM


People also ask

How do I make a div text editable?

Answer: Use the HTML5 contenteditable Attribute You can set the HTML5 contenteditable attribute with the value true (i.e. contentEditable="true" ) to make an element editable in HTML, such as <div> or <p> element.

How do you make an editable content in HTML?

To edit the content in HTML, we will use contenteditable attribute. The contenteditable is used to specify whether the element's content is editable by the user or not. This attribute has two values. true: If the value of the contenteditable attribute is set to true then the element is editable.

What is Contenteditable div?

contenteditable is an HTML attribute that you can add to any HTML element. If its value is true or an empty string, that means that the user can edit it by clicking the element. For example: <div contenteditable="true"> Change me! </ div>


1 Answers

If the content of your editable <div> always consists of a single text node, this is relatively simple and you can use the code below.

var div = document.getElementById("txtarea");
var textNode = div.firstChild;
textNode.data = textNode.data.slice(0, 5) + "more " + textNode.data.slice(5);

Otherwise, you'll need to read about DOM Ranges (note that they are not supported in IE < 9) and use something like this answer to create a range corresponding to character indices within the content and then use insertNode().

var div = document.getElementById("txtarea");
var range = createRangeFromCharacterIndices(div, 5, 5);
range.insertNode(document.createTextNode("more "));
like image 66
Tim Down Avatar answered Sep 19 '22 18:09

Tim Down