function getSelectionHtml(e) {
let html = "";
let fulltext = e.innerHTML;
if (typeof window.getSelection != "undefined") {
let sel = window.getSelection();
if (sel.anchorNode && (sel.anchorNode == sel.extentNode)) {
if (sel.toString() == sel.anchorNode.textContent) {
html = sel.anchorNode.parentElement.outerHTML;
}
}
if (sel.rangeCount) {
let container = document.createElement("div");
for (let 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;
}
}
// si la porcion del texto no se encuentra
// en la cadena completa
if(fulltext.indexOf(html) === -1){
let tmp = html
// coincida sin en el ultimo tag
if( fulltext.indexOf(html.replace(/<[^>]*>$/,"")) !== -1 ){
tmp = html.replace(/<[^>]*>$/,"")
}
// coincida sin el primer tag
else if( fulltext.indexOf(html.replace(/^<[^>]*>/,"")) !== -1 ){
tmp = html.replace(/^<[^>]*>/,"")
}
// coincida sin el primer y ultimo tag
else if( fulltext.indexOf(html.replacematch(/^<[^>]*>/,"").replace(/.*?)<[^>]*>$/,"")[1]) !== -1 ){
tmp = html.replacematch(/^<[^>]*>/,"").replace(/.*?)<[^>]*>$/,"")[1]
}
html = tmp
}
// console.log(html)
alert(html);
}
<!-- le pasamos como paramentro al propio elemento con this-->
<div onmouseup="getSelectionHtml(this)"><span>Lorem ipsum dolor sit amet</span>, <i>consectetur adipiscing elit.</i> <b>Proin finibus laoreet dolor, sed vestibulum</b> mi suscipit id. Donec molestie lectus non neque fringilla, id pulvinar dui suscipit. <i>Etiam congue diam pellentesque finibus congue. Mauris varius faucibus ipsum, vitae consectetur mauris eleifend ac.</i> Quisque dignissim tincidunt dolor, quis molestie ex. Morbi molestie odio et viverra mattis. <b>Proin libero dolor, tincidunt sit amet magna id, semper porta nisl. Duis congue nulla risus, at molestie neque sodales ut.</b> Nam sit amet condimentum dolor. Fusce ullamcorper nibh ac laoreet euismod. Sed vel quam neque. Cras posuere neque at ex accumsan, sed vehicula velit scelerisque. </div>