Skip to content Skip to sidebar Skip to footer

Jquery Getting The Html Of Highlighted Text And Changing Its Style

Saw this post about getting the html from the selected/higlighted text. And it does work in getting the html. function getSelectionHtml() { var html = ''; if (typeof window

Solution 1:

Do this,

function getSelectionHtml() {
  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, range; i < len; ++i) {
        range = sel.getRangeAt(i);
        if (range.startContainer === range.endContainer
            && range.startContainer.nodeType === Node.TEXT_NODE
            && range.startOffset === 0
            && range.endOffset === range.startContainer.length) {
          range.selectNode(range.startContainer.parentElement);
        }
        container.appendChild(range.cloneContents());
      }
      html = container.innerHTML;
    }
  } else if (typeof document.selection != "undefined") {
    if (document.selection.type == "Text") {
      html = document.selection.createRange().htmlText;
    }
  }
  return html;
}

Post a Comment for "Jquery Getting The Html Of Highlighted Text And Changing Its Style"