If I understand you mean correctly, you may want to insert some div element into [contenteditable]
element based on cursor position.
If true, you can try this way:
function append(node) {
var sel = window.getSelection();
var range = sel.getRangeAt(0);
range.deleteContents();
range.insertNode(node);
}
add.addEventListener('click', function () {
var node = document.createElement('div');
node.innerText = 'foo';
node.className = 'test';
append(node);
});
[contenteditable] {
border: 1px solid #ccc;
}
.test {
color: #f00;
display: inline-block;
}
<div contenteditable>Hello world!</div>
<button type="button" id="add">Append text</button>
In this example, you can click on the editor to set cursor position, then clicking on the button to append new div tag.
You can also use this way to append some div tag via input
or keypress
or keydown
... events by detecting character, such as: @ #