I'm trying to create a personal and very simple html editor "contentEditable div based".
And I'm trying to create a function that insert HTML tags around the selected text without removing it format (execCommand insertHTML ruins the formatation).
So I reach this approach:
<div contenteditable="true">
Lorem ipsum dolor <a href='http://www.example.com/'>sit amet</a>, consectetur adipiscing elit. Phasellus convallis sapien quis nisl convallis congue.
</div>
<button id="callFunc">Insert Tag</button>
And my JS:
function insertHTML(tagName) {
var selection = window.getSelection();
var range = selection.getRangeAt(0);
var tag = document.createElement(tagName);
range.surroundContents(tag);
}
callFunc.onclick = e => insertHTML('mark');
It Works very well! Except for one detail! If the selection starts before a node (link, for example) and stops inside this node, the function dont work!
E.g: Suppose the user selects the following piece of text:
(starting at "ipsum" and ending at "sit")
Lorem ipsum dolor sit amet, consectetur adipiscin...
Any Idea how can I solve this? Thanks a lot!!!
Here's a live example:
function insertHTML(tagName) {
var selection = window.getSelection();
var range = selection.getRangeAt(0);
var tag = document.createElement(tagName);
range.surroundContents(tag);
}
callFunc.onclick = e => insertHTML('mark');
<div contenteditable="true">
Lorem ipsum dolor <a href='http://www.example.com/'>sit amet</a>, consectetur adipiscing elit. Phasellus convallis sapien quis nisl convallis congue.
</div>
<button id="callFunc">Insert Tag</button>