How to add <span> tag to a selected text in JQuery

24
December 25, 2018, at 03:00 AM

i have a big paragraph look like this for example

<p> hello this is my paragraph </p>

so i want to append a tag to the selected text in the whole text so if i highlight on "my paragraph" i want the paragraph to be as the following

<p> hello this is <span>my paragraph</span></p>

Thank you all

Answer 1

You can easily do this using javascript by using surroundContents() for this.

<div onclick="addSpanEle()">hello this is my paragraph</div>
function addSpanEle() {
    var span = document.createElement("span");
    if (window.getSelection) {
        var selectedText = window.getSelection();
        if (selectedText.rangeCount) {
            var range = selectedText.getRangeAt(0).cloneRange();
            range.surroundContents(span);
            selectedText.removeAllRanges();
            selectedText.addRange(range);
        }
    }
}

For jquery: check fiddle demo here: http://jsfiddle.net/BGKSN/24/

Courtesy: https://stackoverflow.com/a/17836828/10153495

Answer 2

Find desire contain and wrap with span like below.

$("p:contains('my paragraph')").html(function(_, html) { 
  return html.replace(/(my paragraph)/g, '<span class="yourclass">$1</span>'); 
});
.yourclass { 
  background-color: red 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 
<p> hello this is my paragraph </p>

Answer 3

Good start, but he wants to be able to select text in a div. Try this:

HTML:

<div class="selectMe">
  This is some text 'n stuff. Select part of me and cool stuff will happen!
</div>
<button id="highlight">Make Stuff Happen</button>

CSS:

.selectMe {
  margin-bottom: 2em;
}
button {
  cursor: pointer;
}
.highlight {
  background-color: red;
}

JS:

if (!window.x) {
  x = {};
}
x.Selector = {};
x.Selector.getSelected = function() {
  var t = '';
  if (window.getSelection) {
    t = window.getSelection();
  } else if (document.getSelection) {
    t = document.getSelection();
  } else if (document.selection) {
    t = document.selection.createRange().text;
  }
  return t;
}
$(document).ready(function() {
  $("#highlight").click(function() {
    var selText = x.Selector.getSelected();
    console.log(selText.focusNode);
    if (selText.focusNode.length > 0) {
      var para = $(".selectMe").text();
      para = para.replace(selText, '<span class="highlight">' + selText + '</span>');
      $(".selectMe").html(para);
    } else {
    }
  });
});
Answer 4

I was searching for your answer and found: Add tags around selected text in an element.

Here is the main code that I copied from the provided link.

<p> My sample paragraph </p>
<style>
    span {color: red;}
</style>
<script type="text/javascript">
    function getSelectedText() {
        t = (document.all) ? document.selection.createRange().text : document.getSelection();
        return t;
    }
    $('body').mouseup(function(){
        var selection = getSelectedText();
        var selection_text = selection.toString();
        // How do I add a span around the selected text?
        var span = document.createElement('SPAN');
        span.textContent = selection_text;
        var range = selection.getRangeAt(0);
        range.deleteContents();
        range.insertNode(span);
    });
</script>
READ ALSO
Need assistance on ajax request

Need assistance on ajax request

this is my first time working with $ajax requests, I am currently building a employee directory that should get 12 random people like this:

55
WebRTC simple datachannel example?

WebRTC simple datachannel example?

I am very interested by the webrtc technologyI found some great example for video sharing like this one, made very simple and easy to understand

43
How to create a passwordResetLink using the Firebase admin API?

How to create a passwordResetLink using the Firebase admin API?

I'm trying customize the user experience in my firebase project and hence as well need to create custom email templates including the necessary action links

23