简体   繁体   中英

window.getSelection add class to selection with jquery

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.

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

$(sel).find('img').addClass('myClass');

This will take the selection, turn it into a jQuery object, find the image, and add a class to it.

I have not tested this.

if you want to use javascript you can do:

function addClassName() {
     $('img').addClass('newClass') // adds the class 'newClass' to all image objects
}


<input type='button' onclick='addClassName();' value='addClassName'/>

you can use any selector aside from 'img' in that function as well

var sel= window.getSelection().getRangeAt(0);

$(sel).addClass("someClass");

window.getSelection() will give you the selection, but not the current (or highlighted) selection. You need to use the selection's getRangeAt method for that

获取所选文本的类别

window.getSelection().baseNode.parentElement.className

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM