Jinny Song Jinny Song - 5 months ago 12
Javascript Question

How Can I know the exact paragraph where delete key was down?

Let's say we have a html like below.

<div class="my_content" contenteditable="true">
<div class="my_paragraph"><span style="color:red;">RED</span><span style="color:green;">GREEN</span></div>
<div class="my_paragraph"><span style="font-size:1em">1EM-TEXT</span><div>
<div class="my_paragraph"><span style="font-size:2em">2EM-TEXT</span><div>

And I have a Backbone viewer like below.

events: {
"keydown .my_paragraph" :"onKeyDown"

onKeyDown : function(e) {
if(e.keyCode === 46) { //delete key

Q. In the 'if' at the onKeyDown Method, How can I get the exact-paragraph which is user try to delete (by press delete key)?


You could do something along the lines of:

var cursorTarget = getSelection().getRangeAt(0).commonAncestorContainer.parentNode;
var targetParagraph = $('.my_paragraph').has(cursorTarget);
targetParagraph.addClass('target-paragraph'); // Or whatever you want

Codepen Example (Use spacebar for example)

Also important: You have invalid html. You aren't properly using closing </div> tags in the last two .my_paragraph divs and there is an extra "> after closing the first span.