Search code examples
javascriptwysiwyg

Using javascript to select text and the containing element using createRange


I'm rolling my own generic wysiwyg editor but Im stuck selecting some text. I'm using a div with contenteditable set to true to enter the text into. The problem is I'm using a <var> tag to highlight some text that the user is supposed to delete and rewrite in their own words. When the text inside the <var> tag is clicked it highlights it as I expect but when you hit backspace it only deletes the text and not the tags (<var>). How can I tell the selection to grab a few more characters on each end of the selection so it also deletes the <var> tags? I'm using the following to make the selection happen.

    var range = document.createRange();
    range.selectNodeContents(elem);
    var selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);

Solution

  • Placed function on the div's click event.

    Selected the <var> tag.

    Used .selectNode rather than .selectNodeContents.

    Browsers handle it differently though. Some will add <i></i> tags when you enter more text, others don't, but this does remove the <var> tag completely....

    var myDiv = document.getElementById("myDiv");
    var elem = document.getElementById("myVar");
    myDiv.addEventListener("click", function() {
        var range = document.createRange();
        range.selectNode(elem);
        var selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);            
    });
    <div contenteditable="true" id="myDiv">
    Hello, this<var id="myVar"> is a test</var> of the editor
    </div>