JSFiddle - React, Tailwind, and code Playground
HTML
<div id="editable" contenteditable="true">
<p>A paragraph</p>
<ul>
<li>First list item</li>
<li>Second list item</li>
<li>Third list item</li>
</ul>
</div>
<textarea rows="10" cols="40" id="info"></textarea>
JavaScript
function isSelectionInsideElement(tagName) {
var sel, containerNode;
tagName = tagName.toUpperCase();
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount > 0) {
containerNode = sel.getRangeAt(0).commonAncestorContainer;
}
} else if ( (sel = document.selection) && sel.type != "Control" ) {
containerNode = sel.createRange().parentElement();
}
while (containerNode) {
if (containerNode.nodeType == 1 && containerNode.tagName == tagName) {
return true;
}
containerNode = containerNode.parentNode;
}
return false;
}
document.getElementById("editable").onkeypress = function(evt) {
evt = evt || window.event;
// Check whether the keystroke is the Enter key
if ( (evt.charCode || evt.keyCode) == 13 ) {
// Check whether the craet is within an <li> element
if (isSelectionInsideElement("li")) {
document.getElementById("info").value += "Suppressing Enter keypress inside <li>\n";
return false;
}
}
};