21

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.

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Cruinh
  • 3,611
  • 4
  • 38
  • 45
  • possible duplicate of [How to get selected html text with javascript?](http://stackoverflow.com/questions/5643635/how-to-get-selected-html-text-with-javascript) – Dan Dascalescu Jun 01 '15 at 15:20

3 Answers3

67

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());
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • 3
    +1 for the answer. But I don't get one thing. Under what circumstances will the `else if(typeof document.selection != "undefined")` condition will be true? – Jehanzeb.Malik Apr 23 '13 at 08:22
  • 2
    @Jehanzeb.Malik: In a browser that supports neither `window.getSelection` nor `document.selection`. Admittedly I don't know of any such browser that's still around now, but I prefer to test. – Tim Down Apr 23 '13 at 23:18
  • 1
    This doesn't seem to work so well in IE10. It does support window.getSelection, but document.selection holds the actual data if you're in IE10 + Standards mode. – Jedidja Jun 20 '13 at 14:13
  • @Jedidja: What's the actual problem? Surely IE 10 behaving more like other browsers is a good thing? – Tim Down Jun 20 '13 at 15:04
  • Sorry I should have been clearer. This code doesn't "work" in IE10 + Standards mode because it will actually use window.GetSelection (as it is defined but does not hold the selection information) so the method returns an empty string. – Jedidja Jun 20 '13 at 15:18
  • in IE10 we *want* to use document.selection.createRange() regardless is what I'm trying to say. – Jedidja Jun 20 '13 at 15:19
  • @Jedidja: I haven't seen a problem that severe with `window.getSelection()` in IE 10 (or 9). So there's an IE 10 mode in which `window.getSelection` exists but does not return a selection? If so, is there a similar issue in IE 9 too? – Tim Down Jun 20 '13 at 15:39
  • 1
    @TimDown actually, you know what, I think I'm posting my comments in the wrong question. The problem I'm describing exists when you try to get the selection from a textarea (input), not grabbing pure HTML from the page. I found so many answers from you on this subject I believe I've ended up posting this in the wrong place. – Jedidja Jun 20 '13 at 17:05
  • @TimDown I know this is 10 years old, but, you're a lifesaver. Thank you. – ProjectDiversion Mar 26 '21 at 11:35
10

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

TylerH
  • 20,799
  • 66
  • 75
  • 101
Christian Joudrey
  • 3,441
  • 25
  • 25
  • 6
    Much though I'm tempted to upvote a recommendation for my own library, I'm resisting on the grounds that Rangy is probably overkill for just this one function. – Tim Down Jan 10 '11 at 23:50
  • I thought I remembered correctly that it was @Tim's creation! – David Tang Jan 10 '11 at 23:53
  • I figured I'd suggest it in case he didn't know about it. :) – Christian Joudrey Jan 10 '11 at 23:55
  • as this test was just the first step in a larger project (as you all might guess), I may end up needing Rangy anyway. Thanks! – Cruinh Jan 10 '11 at 23:57
  • @Tim Not that I don't like Google Code, but have you considered making it available on github? :) – Christian Joudrey Jan 11 '11 at 00:10
  • @Christian: If there's an overwhelming reason to do so, I'd happily switch. Google Code may not be the shiny new thing but it seems to do everything I need as main developer and I like the relative simplicity of the layout compared to Github. Is Github significantly better for the user/potential developer? – Tim Down Jan 11 '11 at 00:39
  • @Tim They both have their advantages. Google Code is very simple to use like any other Google product. I'm not particularly fond of SVN, but they support Mercurial now so that's good. I like the social features of Github. You can follow a bunch of projects and be alerted when there are new commits, tracker items, etc. The downside is their free account doesn't offer much. No private repos and 300MB of space. I'm sure there are a few Github vs Google Code posts on SO. Don't get me wrong I didn't want to influence you to change if you are happy with Google Code. :) Was just curious. – Christian Joudrey Jan 11 '11 at 02:14
  • @Christian: thanks for the summary. Looking into moving to Github is now on my (depressingly long) list of things to do. – Tim Down Jan 11 '11 at 09:55
  • 6
    @DanDascalescu could you please refrain from hijacking posts? Thank you - The community – PeeHaa Jun 04 '15 at 13:26
  • @PeeHaa: Beg pardon? What post did I hijack? – Dan Dascalescu Jun 04 '15 at 14:18
  • 3
    @DanDascalescu This one. Fixing a link is fine by me, but adding your opinion to an answer which is not yours is hijacking posts. Tbh I have seen a couple more edits from you that looked like hijacking of posts. E.g. (but not limited to) I have seen a meteor one where you were adding a banner to answers pointing to another answer. I'm sure your intentions are good, but imo edits like [these](http://stackoverflow.com/revisions/11755233/2) or not really needed. We have the upvote / downvote buttons for that. Thanks for your cooperation! – PeeHaa Jun 04 '15 at 14:49
  • 5
    @DanDascalescu - Also, I'm not sure it's appropriate to edit someone else's answer to insert your own commentary: http://stackoverflow.com/posts/7478724/revisions , even if you feel there's an issue with it. You're putting your own words into someone else's mouth, and that's what comments should be used for. These edits of yours are getting flagged all over the site. – Brad Larson Jun 04 '15 at 15:00
  • 1
    @BradLarson: that was not my commentary. It was the commentary of the author of the very library: "I'm resisting on the grounds that Rangy is probably overkill for just this one function.". – Dan Dascalescu Jun 04 '15 at 15:21
  • 1
    So comment on the thing @DanDascalescu. Or answer it yourself. Just stop hijacking posts. Even more so when a mod just told you your edits get flagged... – PeeHaa Jun 04 '15 at 15:22
  • 1
    @BradLarson: Again on the SQL answer you linked, it wasn't my words, but those of the commenter on the post (cucu8). – Dan Dascalescu Jun 04 '15 at 15:22
  • 1
    @PeeHaa: I thought the policy was to *improve* answers? E.g. [this](http://meta.stackoverflow.com/questions/255057/is-it-acceptable-to-improve-other-people-answers-to-your-own-question) or other meta posts I don't have on hand because I have better things to do than stalk SO users. If an answer creates a security hole, I thought it was wide to echo the warning from the comment, which I had independently agreed with. But feel free to revert - I won't have those users on my conscience :) – Dan Dascalescu Jun 04 '15 at 15:27
  • 2
    @DanDascalescu - Edits should be used to improve formatting, fix links, etc., but the spirit and wording of the original answer needs to be respected. Comments are the place for discussion about the potential pitfalls with an answer, and it is up to an answerer to decide if those comments should be incorporated into an answer. Answers should not be edited to insert your own commentary or that of someone else who is not the answerer. What you or they feel to be correct or an improvement may not always be one. – Brad Larson Jun 04 '15 at 15:46
  • 1
    @PeeHaa: how exactly are edits that keep answers up to date not needed? The Meteor one you linked to was useless at best and misleading at worst before my edit. Someone reverted my edit and now [the answer](http://stackoverflow.com/questions/10150538/how-to-expose-a-restful-web-service-using-meteor/11755233#11755233) points to a package that's no longer maintained, and to a wiki page that has been obsoleted for the past two years. Does that increase the quality of the answers on this site, or the quantity of slavish rule enforcements? – Dan Dascalescu Jun 09 '15 at 11:09
  • 1
    @BradLarson: I understand the notion of preserving the spirit of answers, but how does that help the quality of the site? There are many examples of patently wrong answers that have thousands of upvotes because of this ([here's one](http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript)). What the moderation rules seem to ignore is that **users don't bother to read comments** and **original answerers sometimes never come back to their answer**. The example I gave has almost 4000 upvotes and is #1, despite comments since 2011 pointing its glaring flaws. – Dan Dascalescu Jun 09 '15 at 11:18
  • 2
    @BradLarson I just want to echo Dan's thoughts. Do you actually expect each user to read through every comment on every answer searching for the correction to the correction that finally answers the actual question? I come to SO for solutions, not a scavenger hunt. You decrease the effectiveness of your site when you moderate out accurate information and discourage behavior like Dan's. He's done more to help me on this site than any moderator ever has. If he didn't have better things to do I would say he should take one of your jobs. Go ahead, moderate this out :) – kahmali Sep 08 '15 at 11:29
2

Alert boxes do not display HTML, just plain text. You can't get the HTML to show in an alert box.

What you can do is use some JS alert box replacement instead of alert, such as jQuery Dialog, a jQuery plugin, or something else entirely.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • 2
    Not true. `alert("Hi")` will work. The problem is that `window.getSelection().toString()` strips all tags. – David Tang Jan 10 '11 at 23:40
  • @Box9: doesn't work for me. FF 3.6, Windows 7. Pasted this in location bar: `javascript:alert("Hi");` – Jon Jan 10 '11 at 23:42
  • ... which works for me. There's no problem with alerting strings containing HTML, so long as you escape the relevant quotes. – Tim Down Jan 10 '11 at 23:46
  • Works on FF and Chrome on the Mac. I wouldn't try it in the location bar though, use the console. – David Tang Jan 10 '11 at 23:47
  • @Box9, @Tim Down: We 're getting OT here, but I still can't get it to work. Tried from Chrome 9 console too. – Jon Jan 10 '11 at 23:51