简体   繁体   中英

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.

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

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