Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all nodes from selected ranges

For example, I have such text:

Some test <span> in span1</span> sss <span>in span2</span> end of text.

when I select " test in span1 sss in spa" I want to just delete parent spans of selected ranges and create new range that will contain my selected text.

Some<span> test in span1 sss in spa</span>n2 end of text.

I'm using window.getSelection(),range,nodes

Please help!

like image 630
Anuar Sharafudinov Avatar asked Mar 05 '13 05:03

Anuar Sharafudinov


1 Answers

You can do this with the deleteContents(), toString() and insertNode() methods of a range obtained from the selection.

The following will work in all major browsers except IE <= 8. You'll need a different approach for those browsers, which I can outline if you need it.

Demo: http://jsfiddle.net/HUm2K/

Code:

var sel = window.getSelection();
if (sel.rangeCount > 0) {
    var range = sel.getRangeAt(0);
    var newSpan = document.createElement("span");
    var selectedTextNode = document.createTextNode( range.toString() );
    newSpan.appendChild(selectedTextNode);
    range.deleteContents();
    range.insertNode(newSpan);
    range.selectNode(newSpan);
    sel.removeAllRanges();
    sel.addRange(range);
}
like image 128
Tim Down Avatar answered Oct 10 '22 07:10

Tim Down