Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html/Text selection in IE10

I need the ability to select a range of HTML by giving it an ID selector. What I have below works great in Chrome and Firefox, but not in IE 10 (standard mode). (older version of IE are not a concern for this)

function selectElementContents(elementId) {
    var elemToSelect = document.getElementById(elementId);
    var selection= window.getSelection();
    var rangeToSelect = document.createRange();
    rangeToSelect.selectNodeContents(elemToSelect);
    //console.log(rangeToSelect);
    selection.removeAllRanges();
    selection.addRange(rangeToSelect);
}

Demo: http://jsfiddle.net/7Jayc/

The strange part is that the line console.log(rangeToSelect) will absolutely log the correct text in IE 10, but it will not select it.

like image 818
FiniteLooper Avatar asked Sep 11 '13 20:09

FiniteLooper


1 Answers

This worked in all browsers for me:

function selectElementContents(elementId) {
    var elemToSelect = document.getElementById(elementId);

    if (document.createRange) {     // all browsers but IE
        var selection = window.getSelection();
        var rangeToSelect = document.createRange();
        rangeToSelect.selectNodeContents(elemToSelect);
        //console.log(rangeToSelect);
        selection.removeAllRanges();
        selection.addRange(rangeToSelect);
    }
    else {      // IE
        var rangeObj = document.body.createTextRange();
        rangeObj.moveToElementText(elemToSelect);
        rangeObj.select();
    }
}
like image 100
Hanlet Escaño Avatar answered Oct 02 '22 20:10

Hanlet Escaño