Search code examples
javascripthtmlcontenteditable

Selecting the current element in a div


I have a div that has contenteditable set to true. I need to add a class to the <p> element that the user is on. The problem is that contenteditable generates a lot of <p> elements when written in. How do I add the class only to the <p> element that the user is on?

Thanks in advance


Solution

  • You shall use selection.

    This code will give you element where caret is:

    var selObj = window.getSelection(); 
    var element = selObj.focusNode.parentElement;
    

    And now it is up to you what to do with that element.