Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range/Selection get HTML

I have this fiddle: http://jsfiddle.net/Uddaa/

Currently what it does, is when you click on the text, it will make an alert with the text up to that point. What can I do to get the html up to that point instead of just the text?

JavaScript:

$(".content").on("click", function () {
    getBefore();
});

function getBefore() {
    var sel = document.getSelection();
    var off = sel.anchorOffset;
    var ran = sel.getRangeAt(0);
    ran.setStart($(".content").get(0), 0);
    alert(ran.toString());
}

HTML:

<div class="content">
    <p><b>Click</b> anywhere <u>within <em>the</em> text</u> to to see the code up to that point.</p>
</div>
like image 417
Get Off My Lawn Avatar asked Nov 08 '13 14:11

Get Off My Lawn


2 Answers

ran.cloneContents().childNodes[1].innerHTML gives you the complete html.

See jsfiddle or the code snippet.

document.querySelector(".content").addEventListener("click", getHtmlBeforeThis);

function getHtmlBeforeThis(evt) {
  const origin = evt.target.closest(".content");
  if (origin) {
    const selection = document.getSelection();
    const offset = selection.anchorOffset;
    const range = selection.getRangeAt(0);
    range.setStart(origin, 0);
    const upToClickedHtml = range.cloneContents().childNodes[1].innerHTML;
    range.setEnd(origin, 0);
    console.clear();
    console.log(upToClickedHtml);
  }
}
<div class="content">
    <p><b>Click</b> anywhere <u>within <em>the</em> text</u> to to see the code up to that point.</p>
</div>
like image 121
KooiInc Avatar answered Nov 15 '22 19:11

KooiInc


You can use the Rangy library to do this:

rangy.getSelection().toHtml()

Example fiddle

like image 37
Rory McCrossan Avatar answered Nov 15 '22 19:11

Rory McCrossan