window.getSelection add class to selection with jquery

Zebra picture Zebra · Mar 7, 2011 · Viewed 8.2k times · Source

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'/>

Answer

Hussein picture Hussein · Mar 7, 2011

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.

Check working example at http://jsfiddle.net/wP8w9/2/