I want to select an image and a add a class name to the selection. using window.getSelection
.
function addClassName() {
var sel = window.getSelection();
//what goes here???
}
<input type='button' onclick='addClassName();' value='addClassName'/>
To add class to selection, you need to wrap it with <span>
other wise it will not work. Here's the solution.
function addClassToSelection(){
var sel = window.getSelection ? window.getSelection() : document.selection.createRange(); // FF : IE
if(sel.getRangeAt){ // thats for FF
var range = sel.getRangeAt(0);
var newNode = document.createElement("span");
newNode.setAttribute('class', 'someclass');
range.surroundContents(newNode);
} else { //and thats for IE7
sel.pasteHTML('<span class="someclass">'+sel.htmlText+'</span>');
}
}
This should guide you in the proper direction. Modify it as you see fit.