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>
                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>
You can use the Rangy library to do this:
rangy.getSelection().toHtml()
Example fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With