javascripthtmlmedium-editor

Get last focused element of contenteditable div


I am using Medium editor rich text editor library which set contenteditable='true' of a parent div. The problem I am getting with this is, I am not able to get the last focused element inside this editor.

Actually, I have a button outside of this editor. When I click on that button, I have to pass the reference of the last focused child DOM node on which I was in medium editor. I tried some functions provided inside medium editor documentation but that didn't work for me.

I have elements like below in my DOM:

<div class="story-content medium-editor-element" contenteditable="true" spellcheck="true" data-medium-editor-element="true" role="textbox" aria-multiline="true" data-medium-editor-editor-index="1" medium-editor-index="13e73c5b-f038-619c-7913-8a15d4f5c7e6" data-medium-focused="true">
    <p class="empty" data-placeholder="Your story...">1</p>
    <p class="empty" data-placeholder="Your story...">2</p>
    <p class="empty" data-placeholder="Your story...">3</p>
    <p class="empty" data-placeholder="Your story...">4</p>
</div>

I have to pass the reference of p element with innerHTML=4 because that was the last child element on which I was focused and after that I clicked on the button.

Can anyone please help with the same?

Thanks.


Solution

  • I was able to get it by editor.getSelectedParentElement(); method.

    We can use this method inside the change event of the editor.