How to find the paragraph at the cursor?

37 views Asked by At

I'm writing a HTML editor and using javascript or jquery I need to find the paragraph element under the cursor, not the mouse pointer but the cursor. I have the button that adds an indented paragraph, but I'm have trouble find the paragraph for the button to remove it.

I've tried a bunch like it:

    function getCursorPosition() {
        var editor = document.querySelector("#main");
        if(window.getSelection()){
            var sel = window.getSelection();
            if(sel.getRangeAt){
                var pos = sel.getRangeAt(0).startOffset;
                var endPos = pos + Array.from(editor.innerHTML.slice(0,pos)).length -  editor.innerHTML.slice(0,pos).split("").length;
                return endPos;
            }
        }
        return null;
    }

But if there are any HTML tags the "conteneditable" element it give me the wrong location. It's in reference the the tag and the tags size is not included. HELP??

0

There are 0 answers