0

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>' );}
    }
Wiram Rathod
  • 1,895
  • 1
  • 19
  • 41
  • Did you try [append](http://api.jquery.com/append/)? `$( '#content_area ('+range+')' ).append( '
    ' );` Also, I imagine Rangy has methods to do this. Take a look at the [addRange](https://code.google.com/p/rangy/wiki/RangySelection#Methods) documentation.
    – d_ethier Apr 25 '13 at 13:07
  • when you say its not working, are you getting an error in your browser, or is your input field not adding on? – klewis Apr 25 '13 at 13:15
  • hi blachwk I got this error: Timestamp: 4/25/2013 6:48:02 PM Error: Error: Syntax error, unrecognized expression: (demands ) Source File: http://code.jquery.com/jquery-1.7.2.min.js Line: 3 – Wiram Rathod Apr 25 '13 at 13:19

2 Answers2

3

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);
}
Tim Down
  • 318,141
  • 75
  • 454
  • 536
1

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);
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
  • Nice, but does not work for selections spanning multiple nodes. And wouldn't you always have text nodes? You select text after all. – a better oliver Apr 25 '13 at 13:55