Search code examples
jquerycontenteditable

How to identify a active contentEditable div inside another div which has multiple contentEditable divs


Here is the simple markup:

<div id="myId1">
    <div id="contentEdit1" contentEditable="true></div>
    <div id="contentEdit2" contentEditable="true></div>
    ...
</div>

Here is the jQuery code:

$('#myId1 ' + '[contenteditable="true"]').on('keydown', function(ev) {
    console.log($(this).attr('id'));
});

The problem is that the event handler is not triggered at all when I start editing any of the contentEditable divs. Any thoughts?

EDIT: I had a typo in my question. I had missed the single quotes around [contenteditable="true"] and the closing parenthesis of console.log.


Solution

  • Try

    $('#myId1 [contenteditable="true"]').on('keydown', function(ev) {
        console.log($(this).attr('id'));
    });
    

    Demo - https://codepen.io/vyspiansky/pen/vYGgEZj

    Actually you have a wrong element selector '#myId1 ' + [contenteditable="true"] + do not close the parenthesis after console.log.