Youll want to use the selections api to do this. You can use containsNode
to do the rest, if your are ie9+.
https://developer.mozilla.org/en-US/docs/Web/API/Selection
Assuming you can use containsNode
you should just be able to listen to keydown
, filter by Enter
, and then finaly query the document for the selection and apply classes depending on if the block nodes are contained within the selection.
const $root = document.querySelector('.root');
document.addEventListener('keydown', (e) => {
if (e.code == "Enter") {
const selection = document.getSelection();
console.log(selection)
for (const $child of $root.children) {
if (selection.containsNode($child) || $child.contains(selection.anchorNode) || $child.contains(selection.focusNode)) {
$child.classList.add('selected');
} else {
$child.classList.remove('selected');
}
}
}
});
This code was thrown together in about 3 minutes, is sub optimal, and should be reviewed before being used. You can see it in action @ https://jsfiddle.net/z0gh7eck/2/.