How to select the text of a span on click?

前端 未结 4 2019
旧时难觅i
旧时难觅i 2021-01-31 18:19

I am looking for a way to select the text inside a span using jquery when the text is clicked on.

For example in the html snippet below, I want the text \"\\apples\\ora

4条回答
  •  逝去的感伤
    2021-01-31 18:44

    It could be implemented with native JavaScript. A working demonstration on jsFiddle. Your code could be like this:

    $('.unc_path').click(function (){
        var range, selection;
    
        if (window.getSelection && document.createRange) {
            selection = window.getSelection();
            range = document.createRange();
            range.selectNodeContents(this);
            selection.removeAllRanges();
            selection.addRange(range);
        } else if (document.selection && document.body.createTextRange) {
            range = document.body.createTextRange();
            range.moveToElementText(this);
            range.select();
        }
    });
    

提交回复
热议问题