JSFiddle - React, Tailwind, and code Playground

by AndyFl

HTML

<p>Random content <span>here <i>and</i> other</span> random content here.</p>
<p>This random content is here <span> within the span </span> <strong>other random content</strong> is here.</p>

<pre></pre>

JavaScript

$.fn.selection = function(options) {

  var $el = this,
    lastSelections = [],
    $settings = $.extend({}, $.fn.selection.defaults, options);

  function removeCloseTags(range, selectionText) {
    if (range.endOffset < range.endContainer.length) {
      selectionText = selectionText.replace(
        new RegExp('<\/' + range.endContainer.parentElement.localName + '>(<\/[a-z]+>)*', 'gm'),
        ''
      );
    } else {
      var sibling = range.startContainer.nextSibling;

      if (sibling != null) {
        var siblingName = sibling.localName,
          contents = new RegExp('<' + siblingName + '>(.*)<\/' + siblingName + '>', 'gm').exec(selectionText);

        if (contents != null && typeof contents[1] != 'undefined' && sibling.innerHTML != contents[1]) {
          selectionText = selectionText.replace(
            new RegExp('<\/' + siblingName + '>(<\/[a-z]+>)*', 'gm'),
            ''
          );
        }
      }
    }

    return selectionText;
  }

  function removeOpenTags(element, selectionText) {
    var sibling = element.parentElement;

    if (selectionText.indexOf(sibling.innerHTML) != 0) {
      selectionText = selectionText.replace(
        new RegExp('^(<[a-z]+>)*<' + sibling.localName + '>', 'gm'),
        ''
      );
    }

    return selectionText;
  }

  function getSelectionText(container, selection, range) {
    var selectionText = container.innerHTML;

    container.innerHTML = '';
    container.appendChild(range.cloneContents());
    selectionText = container.innerHTML;

    if ($settings.removeCloseTags) {
      selectionText = removeCloseTags(range, selectionText);
    }

    if ($settings.removeOpenTags) {
      selectionText = removeOpenTags(range.startContainer, selectionText, 0);
    }

    return selectionText;
  }

  function getSelections() {
    lastSelections = [];

    if (typeof window.getSelection != 'undefined') {
      var selection = window.getSelection(),
        container = document.createElement('div');

      if...