Here is the jsFiddle of what I am trying to achieve.
HTML:
<div id="replaceme" contenteditable>Hello I am to be replaced. But the cursor position inside this div needs to be retained after replacement.</div>
<button>REPLACE</button>
JavaScript:
btn = document.querySelector('button')
btn.onclick = function() {
var replace = document.querySelector("#replaceme");
replace.outerHTML = '<p id="replaced" contenteditable>' + replace.innerHTML + '</p>';
}
Basically, there is a div
with some content and it's editable. The element need not be just div
. It could be anything like p
or h1
etc.
I am going to do the following:
Place the cursor inside the div. Let's say I place my cursor after the text 'Hello I am to be replaced.'
Click the button 'REPLACE'. This basically replaces the
div
withp
but innerHTML of the newp
is same as the olddiv
.Now the cursor position is lost as I am having a new set of DOM elements, even though the contents of the dom are same.
Basically, I want to replace the tag without losing the caret position and I am not using jQuery for this project.