Search code examples
javascriptjqueryrangy

JQuery, how to append div after selected text in html?


Hi is that possible to add div after selected text? with jQuery or java-script and rangy js

I'm try with below code but not working..

function pin_surroundRange() {
    var range = getFirstRange(); //get selected text via rangy js 
    if(range != null) {
        $( '#content_area ('+range+')' ).replaceWith( ''+range+'<div><input type="text" /></div>' );}
    }

Solution

  • The steps I'd use are:

    • Get the selected range
    • Collapse the range to the end
    • Call the range's insertNode() method

    Code:

    var div = document.createElement("div");
    div.appendChild( document.createElement("input") );
    
    var sel = rangy.getSelection();
    if (sel.rangeCount > 0) {
        var range = sel.getRangeAt(0);
        range.collapse(false);
        range.insertNode(div);
    }