Html/Text selection in IE10
Asked Answered
M

1

6

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.

Marmot answered 11/9, 2013 at 20:2 Comment(3)
As it turns out, this code was working for me in IE 10, but I was running into another bug with IE where this wouldn't work correctly when displayed in a modal window. I changed the layout of the page and this works fine now.Marmot
were you able to select text inside a modal window in IE?Baltoslavic
No, it was not working in a modal in IE10.Marmot
D
2

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();
    }
}
Dahl answered 11/9, 2013 at 20:57 Comment(2)
Thanks, but see my comment above on the original question. This code is good, but not specific to IE 10. The case for IE here actually is for IE9 and lower I believe, not IE 10.Marmot
I know, I'm just saying that document.createRange exists in IE 10, and that is why it works there. The else case is not needed since it is for IE <=9 and I don't need to support it.Marmot

© 2022 - 2024 — McMap. All rights reserved.