Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return HTML from a user-selected text

Tags:

I have the following, very simple html page:

<html>     <head>     <script type="text/javascript">         function alertSelection()         {             var selection = window.getSelection();             var txt = selection.toString();             alert(txt);         }     </script>     </head>     <body>         This is <span style="background-color:black;color:white">the</span> text.         <div style="background-color:green;width:30px;height:30px;margin:30px"             onmouseover="alertSelection()">     </body> </html> 

When I select the entire first line and mouseover the square, I get an alert with "This is the text.".

How would I fix this so the span tag or any other selected HTML isn't stripped out of the alert message?

edit: I'm looking specifically for how to get the full HTML from window.getSelection(). The alert dialog was just how I was attempting to validate the code. I'm only concerned about this working in Safari.

like image 556
Cruinh Avatar asked Jan 10 '11 23:01

Cruinh


People also ask

How do you return text in HTML?

The <br> HTML element produces a line break in text (carriage-return). It is useful for writing a poem or an address, where the division of lines is significant.

What is getSelection in Javascript?

getSelection() The Window. getSelection() method returns a Selection object representing the range of text selected by the user or the current position of the caret.

What does text () do in Javascript?

The text() method sets or returns the text content of the selected elements. When this method is used to return content, it returns the text content of all matched elements (HTML markup will be removed). When this method is used to set content, it overwrites the content of ALL matched elements.


2 Answers

Here's a function that will get you HTML corresponding to the current selection in all major browsers:

function getSelectionHtml() {     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;         }     }     return html; }  alert(getSelectionHtml()); 
like image 124
Tim Down Avatar answered Sep 28 '22 12:09

Tim Down


Use Rangy: https://github.com/timdown/rangy

Cross-browser range and selection library.

Check out the demos here: http://rangy.googlecode.com/svn/trunk/demos/index.html

like image 41
Christian Joudrey Avatar answered Sep 28 '22 11:09

Christian Joudrey