This is the code for the fiddle link link
In this the span I click is appended to the content in the div but I want that instead of appending it inserts to the particular location of cursor.
document.querySelector('.selectable-icons').addEventListener('click', function(e) {
 
    document.querySelector('[contenteditable]').appendChild(e.target.cloneNode(true));
  
});
document.querySelector('div').addEventListener('keydown', function(event) {
    // Check for a backspace
    if (event.which == 8) {
        s = window.getSelection();
        r = s.getRangeAt(0)
        el = r.startContainer.parentElement
        // Check if the current element is the .label
        if (el.classList.contains('label')) {
            // Check if we are exactly at the end of the .label element
            if (r.startOffset == r.endOffset && r.endOffset == el.textContent.length) {
                // prevent the default delete behavior
                event.preventDefault();
                if (el.classList.contains('highlight')) {
                    // remove the element
                    el.remove();
                } else {
                    el.classList.add('highlight');
                }
                return;
            }
        }
    }
    event.target.querySelectorAll('span.label.highlight').forEach(function(el) { el.classList.remove('highlight');})
});
[contenteditable] {
  border: 1px solid #000;
  margin: 0.4em 0;
  line-height: 1.4em;
  -webkit-appearance: textfield;
  appearance: textfield;
}
img {
  vertical-align: top;
  max-height: 1.4em;
  max-width: 1.4em;
}
.selectable-icons img {
  cursor: pointer;
}
span.label.highlight {
    background: #E1ECF4;
    border: 1px dotted #39739d;
}
<p>Just click on an icon to add it.</p>
<div class="custom-input">
  <div class="selectable-icons">
    <span class="label"> Ingredient1 </span> 
    <span class="label">INGREDIENT 2</span> 
      <span class="label">INGREDIENT 3</span>  
  </div>
  <div contenteditable="true">
    You can type here. Add an icon.
  </div>
</div>
I tried the one solution suggested in this link
In the provided link there's a button I used span instead. When I click on span the
window.getSelection
returns the span element with onClick event. The focus shifts to that span