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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With