The code below works, it inserts to cursor position, but I need to be sure the node is added only to div mydiv
and not to other part of the page. For example the other div another
. With this code if I click on other positions different from mydiv
the span is added there.
Can you suggest me a clean approach to solve this?
Can I use something like
if(window.getSelection().parentNode.id != "mydiv") return;
if (window.getSelection().rangeCount == 0) var a = document.createRange(); else var a = window.getSelection().getRangeAt(0);
<div id="mydiv" contenteditable="true">
This text can be edited by the user.
</div>
<div id="another"></div>
<a href="" onclick="addShort('Hello','Bye')" >Test</a>
function addShort(id,name,custom=null){
var a = _range;
var b = _selectedText;
var z = document.createElement("span");
b = " <span data-id='"+id+"' data-type=\""+custom+"\"><span
contenteditable=\"true\" > "+name+" </span></span> ";
z.innerHTML=b;
a.deleteContents();
a.insertNode(z);
}
if (window.getSelection().rangeCount == 0)
var a = document.createRange();
else
var a = window.getSelection().getRangeAt(0);
_range = a;
_selectedText = a.toString();
e.preventDefault;
});