The InsertHTML
command does not work in IE. However, IE's TextRange
object has a convenient pasteHTML()
method that you can use instead.
Live demo: http://jsfiddle.net/RmXgy/1/
Code:
function getSelectedText() {
var selectedText = "", sel;
if (window.getSelection) {
selectedText = "" + window.getSelection();
} else if ( (sel = document.selection) && sel.type == "Text") {
selectedText = sel.createRange().text;
}
return selectedText;
}
var sel, html = '<span style="background-image: url(foo.png)">'
+ getSelectedText() + "</span>";
if ( (sel = document.selection) && sel.type != "Control") {
sel.createRange().pasteHTML(html);
} else {
document.execCommand("InsertHTML", false, html);
}