HTML / text selection in IE10

I need the ability to select an HTML range by providing it with an identifier selector. What I have below works fine in Chrome and Firefox, but not in IE 10 (standard mode). (older version of IE does not bother with 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 string console.log(rangeToSelect) will correctly write the correct text in IE 10, but will not select it.

+6
source share
1 answer

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

Source: https://habr.com/ru/post/953651/


All Articles