skip to Main Content

Let’s say we have a contenteditable div, and inside the div there is a ul

<div contenteditable="true">
<ul>
<li>Some text here</li>
<li>Some more te|<- CARET HERExt</li>
</ul>
</div>

I need to get the node that the caret is inside, as well as the caret’s index inside the innerText.
I have used the following code:

let selection = getSelection();
console.log(selection.focusNode);
console.log(selection.focusOffset);

Expected output:

<li>
12

Actual output:

<ul>
3

2

Answers


  1. Chosen as BEST ANSWER

    Thank you @ram singh for your answer. I adapted it slightly for my use - here is the code:

    let selection = getSelection();
    // console.log(selection);
    let selection_focus_node, selection_focus_offset;
    if (selection && selection.focusNode) {
        selection_focus_node = selection.focusNode;
        selection_focus_offset = selection.focusOffset;
    
        while (selection_focus_node.childNodes[0] && selection_focus_node.nodeType !== Node.TEXT_NODE) {
            selection_focus_node = selection_focus_node.childNodes[0];
        }
    }
    else {
        console.log("No selection or focusNode is null");
    }
    

  2. user below code

        <div contenteditable="true">
            <ul onclick="getCaretDetails()">
            <li>Some text here</li>
            <li>Some more te|<- CARET HERExt</li>
            </ul>
            </div>
            <script>
            function getCaretDetails() {
                let selection = getSelection();
                
                if (selection && selection.focusNode) {
                    let focusNode = selection.focusNode;
                    let focusOffset = selection.focusOffset;
    
                    // Traverse up to find the text node if necessary
                    while (focusNode && focusNode.nodeType !== Node.TEXT_NODE) {
                        focusNode = focusNode.childNodes[0];
                    }
    
                    if (focusNode && focusNode.nodeType === Node.TEXT_NODE) {
                        console.log('Node:', focusNode.parentNode); // Parent element of the text node
                        console.log('Index in text:', focusOffset);
                    } else {
                        console.log('Caret is not within a text node.');
                    }
                } else {
                    console.log('No selection or focusNode is null.');
                }
            }
    
    
    
            </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search