How to get selection text across multiple HTML elements?

Here is my question:

When a user makes a choice in an article or in the editing area of ​​a WYSWYG editor’s widget, the selection can span several elements, like anchors, images, span tags ... even block level elements (but there is no table in my task).

I know how to get a Range object from a selection, but could not find a reliable solution to get the text of the contents of a Range object.

I am not looking for a solution for IE (its TextRange object has a .text property).

Thanks!

+4
source share
2 answers

Have you viewed the quirksmode article in Range?

Based on this article, you can create a method like this:

 function getRangeText() { var userSelection; if (window.getSelection) { userSelection = window.getSelection(); } else if (document.selection) { userSelection = document.selection.createRange(); } var selectedText = userSelection; if (userSelection.text) { selectedText = userSelection.text; } return selectedText; } 

I tested this on FF5, Opera 11, Safari on Mac, as well as IE6 and IE7. This is worth checking out in other IE browsers, but I think it works in them too.

+4
source

This returns a string and works in all major browsers:

 function getSelectionText() { var text = "" if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection && document.selection.type == "Text") { text = document.selection.createRange().text; } return text; } 
+2
source

All Articles