2

I want to get HTML source of select text in div and alert that.

This is my code:

if (!window.x) {
    x = {};
}
x.Selector = {};
x.Selector.getSelected = function() {
    var t = '';
    if (window.getSelection) {
        t = window.getSelection();
    } else if (document.getSelection) {
        t = document.getSelection();
    } else if (document.selection) {
        t = document.selection.createRange().text;
    }
    return t;
}

$(function() {

    $(document).bind("mouseup", function() {
        var mytext = x.Selector.getSelected();
        alert(mytext);
    });

Source

But that return text plain.

Is there any way?

Thanks for any help.

Community
  • 1
  • 1
Morteza
  • 2,143
  • 7
  • 37
  • 61
  • Do you mean this as in, the selected text along with any markup it contains? So if the selection had bold text in it, it would include the `` tags? – Armatus Apr 07 '12 at 15:58

2 Answers2

3

http://www.codingforums.com/showthread.php?t=154848#post762994 suggests the following:

function selHTML() {

    if (window.ActiveXObject) {
        var c = document.selection.createRange();
        return c.htmlText;
    }

    var nNd = document.createElement("p");
    var w = getSelection().getRangeAt(0);
    w.surroundContents(nNd);
    return nNd.innerHTML;
}

Google is good (often anyway) :-)

Demo: http://jsfiddle.net/rR8Sh/1/ I added plain text selection in case a tag is incompletely selected and used span instead of p to avoid adding a line break. It will still add the empty <span> though; I couldn't think of a way to avoid that.

Armatus
  • 2,206
  • 17
  • 28
  • 1
    Your fiddle is missing `});` at the end. It works but 1) you have to select the whole link, you can't select a part only and 2) at least in FF, `surroundContents` actually inserts the `

    ` created by the script, adding a line break.

    – Armatus Apr 07 '12 at 17:08
  • Edited the answer to include that. – Armatus Apr 07 '12 at 17:35
  • @Amatus, i am trying to do the exact thing as in the question, but ur fiddle answer , displays only the text, it is not returning the html of the selected text, any help would be appreciated. – Pbk1303 Nov 22 '15 at 17:56
1

If I understand correctly, you want to get the HTML of the selected node? Try this:

function getSelectedNode() {
    if (document.selection) {
        return document.selection.createRange().parentElement();
    } else {
        var selection = window.getSelection();
        if (selection.rangeCount > 0)
                return selection.getRangeAt(0).startContainer.parentNode;
    }
}

Borrowed from this answer.

Community
  • 1
  • 1
Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123