1

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>&nbsp;";

  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;   
    
}); 
Robert
  • 59
  • 1
  • 5
  • https://stackoverflow.com/questions/8339857/how-to-know-if-selected-text-is-inside-a-specific-div Maybe this helps you. – Atr0x Jun 25 '20 at 14:04
  • if (window.getSelection().rangeCount == 0) var a = document.createRange(); else var a = window.getSelection().getRangeAt(0); _range = a; _selectedText = a.toString(); e.preventDefault; }); – Robert Jun 25 '20 at 14:05
  • your edited function has syntax issues and doesnt seem complete.... – Suraj Rao Jun 25 '20 at 14:08
  • Please provide a proper [mre] of the issue. – CBroe Jun 25 '20 at 14:08
  • [`Selection`](https://developer.mozilla.org/en-US/docs/Web/API/Selection) has properties `anchorNode` (“Returns the Node in which the selection begins.”) and `focusNode` (“Returns the Node in which the selection ends.”) - so I’d try to use those to figure out, whether your current selection is inside of your target element, or not. That probably doesn’t cover the case that the selection starts before and/or ends after your target node. Suppose in that case, you can only alert the user to that fact, and reject the operation? – CBroe Jun 25 '20 at 14:14
  • gets the last selection made on the page and us it to insert the span, is there a way to get "a" only if selection is made within a div with give class name? – Robert Jun 25 '20 at 15:27
  • 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); – Robert Jun 25 '20 at 15:36

0 Answers0