Html/Text selection in IE10

1.4k Views Asked by At

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.

1

There are 1 best solutions below

2
On

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();
    }
}