1

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>
user3787036
  • 191
  • 10
  • Does this answer your question? [How To Wrap / Surround Highlighted Text With An Element](https://stackoverflow.com/questions/6328718/how-to-wrap-surround-highlighted-text-with-an-element) – imvain2 Jun 22 '20 at 19:26
  • Thanks, @imvain2! But it doesn't! Actually, this sugestion throws the same error as mine when user selects just part of a link! – user3787036 Jun 22 '20 at 19:56

0 Answers0