Reputation: 5591
I have div with contenteditable:
<div class="example" contenteditable="true">This is an example</div>
Using innerHTML
, I get "This is an example".
Now at 7th position (right after "is"), I want to add a html (<span class="yup">NOT</span>
) to give the following (either using click
, focus
what-not)
<div class="example" contenteditable="true">This is <span class="yup">NOT</span> an example</div>
Knowing the caret position and innerHTML, how would I add a html into it?
I thought about using substr
then .html(content)
, but that's replacing the whole content and I want to avoid it. I want to simply add a content directly at a specific position.
For example: Replacing the whole content and what I DON'T want to do.
c = c.substr(0, e) + '<span class="yup">NOT</span>' + c.substr(e)';
$("div.example").html(c);
Instead of replacing it, I want to just "inject" it.
Any suggestions will be much appreciated.
Upvotes: 2
Views: 2612
Reputation: 65808
Strings are immutable in JavaScript, you can't modify the content without creating a new one.
This is about as close as you can get (on par with substr
and substring
).
// Store the new data
var newOutput = " <span class='yup'>NOT</span> ";
// Get a reference to the target div
var theDiv = $("div.example");
// Split the current content of the div where there are spaces
// and return the individual words into a new array
var words = theDiv.text().split(/\s+/g);
// Inject the right pieces of the array along with spaces and the new content
// into the div
theDiv.html(words[0] + " " + words[1] + newOutput + words[2] + " " + words[3]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="example" contenteditable="true">This is an example</div>
But, if you have the opportunity to generate the content of the div
from pure JavaScript, then you can inject the correct string just once, like this (run this snippet several times so that you can see the div's content change as various random numbers are generated).
// Store the new data
var output1 = "This is an example.";
var output2 = "This is <span class='yup'>NOT</span> an example.";
// Get a reference to the target div
var theDiv = $("div.example");
// Inject the correct string into the div based on some criteria
var x = Math.random() > .5;
x === true ? theDiv.html(output1) : theDiv.html(output2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="example" contenteditable="true">This is an example</div>
Upvotes: 2
Reputation: 2582
You can't change the HTML-string of an element without setting the whole content. I would recommend putting the <span class="yup">NOT</span>
already in place but making it invisible with CSS. Then if it is toggled you just make it visible with Javascript.
Upvotes: 3