Question

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>' );}
    }
Was it helpful?

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);
}

OTHER TIPS

I've created a simple function that works for text nodes. I believe you can achive the same result for element nodes with some additional effort.

http://jsfiddle.net/tarabyte/HTYhm/4/

var addDiv = function() {
    rangy.init(); //This might be somewhere else
    var sel = rangy.getSelection();
    if(sel && sel.anchorNode && sel.anchorNode.nodeType === 3 ) { //For text nodes only
        var node = $(sel.anchorNode),
            text = node.text(),
            length = Math.max(sel.focusOffset, sel.anchorOffset); 

        node.replaceWith(text.substring(0, length) 
                         + "<div> <input name='edit'/></div>" 
                         + text.substring(length ));
    }
}
$("#mark").on("click", addDiv);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top