Lazhar Lazhar - 7 months ago 9
HTML Question

Get the HTML source code of the selected text?

I have a page with a blog article on it. People can select part of this article and I want to store the part they have select, but not just the text on screen, the HTML source.

Example, the screen shows;


The Boerboel Breeders Association was established in 1983 in the Senekal district.


Where the full code is:

<p>
The Boerboel Breeders Association was <strong>established in 1983</strong> in the Senekal district.
</p>


So I want that when somebody selects "was established in 1983 in the Senekal district" it returns to me the source code as per:

was <strong>established in 1983</strong> in the Senekal district


I am using Javascript & jQuery.

Answer

Use window.getSelection() like as follows,

function alerttext(){
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;
    }
}
 alert(html);
}
<p>
    The Boerboel Breeders Association was <strong>established in 1983</strong> in the Senekal district.
</p>

<button onclick="alerttext()">ALERT</button>