SANDEEP
SANDEEP

Reputation: 1082

IE8 does not return selected text using mouse pointer

I'm using this code to select text from the window document. This code is working fine in all browsers: it returns the selected text, but in IE8 it does not give the selected text. Instead it gives the whole HTML of the selected line. Can anybody give me solution for this?

Example:

<B><U><SPAN style="LINE-HEIGHT: 150%; FONT-FAMILY: 'Arial',
'sans-serif'; FONT-SIZE: 12pt">Summary</SPAN></U></B> 

I want only Summary so all major browser return this except IE8.

<script type="text/javascript">
    function getSelectionText(id) {
        var html = "";
        if (typeof window.getSelection != "undefined") {
            var sel = window.getSelection();
            if (sel.rangeCount) {
                var container = document.createElement("div");
                for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                    container.appendChild(sel.getRangeAt(i).cloneContents());
                }
                html = container.innerHTML;
            }
        } else if (typeof document.selection != "undefined") {
            if (document.selection.type == "Text") {
                html = document.selection.createRange().htmlText;
            }
        }
        document.getElementById(id).value = html;
        //document.getElementById(id).value = html;
    }       
</script>

Upvotes: 3

Views: 585

Answers (3)

Mark Walters
Mark Walters

Reputation: 12390

The issue is with the following line in IE8

html = document.selection.createRange().htmlText;

Change it to this

html = document.selection.createRange().text;

Below is a nice simple function which seems to work well for me

function getSelectedText() {
  var txt = '';
  if (window.getSelection) {
    txt = window.getSelection();
  }
  else if (document.getSelection) {
    txt = document.getSelection();
  }
  else if (document.selection) {
    txt = document.selection.createRange().text;
  }
  else return; 
  return txt;
}

Hope this helps

Upvotes: 0

Daidai
Daidai

Reputation: 557

Change

html = container.innerHTML;

into

html = container.innerText;

Upvotes: 0

Mathijs Flietstra
Mathijs Flietstra

Reputation: 12974

You should look into rangy - A cross-browser JavaScript range and selection library. In their own words:

It provides a simple standards-based API for performing common DOM Range and Selection tasks in all major browsers, abstracting away the wildly different implementations of this functionality between Internet Explorer up to and including version 8 and DOM-compliant browsers.

Upvotes: 1

Related Questions