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!
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With