Unable to type inside contenteditable span

Discussão em 'Angular' iniciado por Kartik Watwani, Fevereiro 11, 2025.

  1. I have a parent contenteditable div. Inside it I have a child contenteditable span element. Now, what I want is when my div is empty and I click inside the div. I want the cursor to be such that the content I type should be placed inside child contenteditable span element. I have tried below code but still the typed content is coming as a text node before the span.

    HTML

    <div id="input" contenteditable="true">
    <span contenteditable="true" id="first"></span>
    </div>


    TS

    function setCaret() {
    var element = document.getElementById("input");
    var range = document.createRange();
    var node;
    node = document.getElementById("first");
    range.setStartAfter(node);
    var sel = window.getSelection();
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
    element.focus();
    }


    Now let's say I click inside div and type "Kartik". The result that I am looking for is:

    <div id="input" (focus)="setCaret()" contenteditable="true">
    <span contenteditable="true" id="first">Kartik</span>
    </div>


    But I am getting:

    <div id="input" (focus)="setCaret()" contenteditable="true">
    Kartik
    <span contenteditable="true" id="first"></span>
    </div>


    JS Fiddle

    Can you help me with this?

    PS: I know I can tinker with document object by removing the text node and then putting that inside span element, but I am not looking for that solution because in Angular I am facing some issues when I am manually changing the DOM instead of relying on property binding.

    Continue reading...

Compartilhe esta Página