Return HTML from a user-selected text
Asked Answered
F

3

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.

Factious answered 10/1, 2011 at 23:31 Comment(1)
possible duplicate of How to get selected html text with javascript?Hymnology
E
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());
Erda answered 10/1, 2011 at 23:45 Comment(9)
+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?Maragretmarala
@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.Erda
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.Jyoti
@Jedidja: What's the actual problem? Surely IE 10 behaving more like other browsers is a good thing?Erda
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.Jyoti
in IE10 we want to use document.selection.createRange() regardless is what I'm trying to say.Jyoti
@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?Erda
@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.Jyoti
@TimDown I know this is 10 years old, but, you're a lifesaver. Thank you.Sudorific
S
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

Sensitize answered 10/1, 2011 at 23:47 Comment(20)
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.Erda
I thought I remembered correctly that it was @Tim's creation!Halleyhalli
I figured I'd suggest it in case he didn't know about it. :)Sensitize
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!Factious
@Tim Not that I don't like Google Code, but have you considered making it available on github? :)Sensitize
@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?Erda
@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.Sensitize
@Christian: thanks for the summary. Looking into moving to Github is now on my (depressingly long) list of things to do.Erda
@DanDascalescu could you please refrain from hijacking posts? Thank you - The communityOmbre
@PeeHaa: Beg pardon? What post did I hijack?Hymnology
@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 or not really needed. We have the upvote / downvote buttons for that. Thanks for your cooperation!Ombre
@DanDascalescu - Also, I'm not sure it's appropriate to edit someone else's answer to insert your own commentary: 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.Gunpowder
@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.".Hymnology
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...Ombre
@BradLarson: Again on the SQL answer you linked, it wasn't my words, but those of the commenter on the post (cucu8).Hymnology
@PeeHaa: I thought the policy was to improve answers? E.g. this 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 :)Hymnology
@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.Gunpowder
@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 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?Hymnology
@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). 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.Hymnology
@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 :)Bwana
F
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.

Fortunna answered 10/1, 2011 at 23:32 Comment(5)
Not true. alert("<b>Hi</b>") will work. The problem is that window.getSelection().toString() strips all tags.Halleyhalli
@Box9: doesn't work for me. FF 3.6, Windows 7. Pasted this in location bar: javascript:alert("<b>Hi</b>");Fortunna
... which works for me. There's no problem with alerting strings containing HTML, so long as you escape the relevant quotes.Erda
Works on FF and Chrome on the Mac. I wouldn't try it in the location bar though, use the console.Halleyhalli
@Box9, @Tim Down: We 're getting OT here, but I still can't get it to work. Tried from Chrome 9 console too.Fortunna

© 2022 - 2024 — McMap. All rights reserved.