Ways to incorporate the <span> tag into a chosen text using JQuery

Here is an example of a big paragraph:

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

I am looking to add a tag to the selected text within the entire paragraph. For instance, if I highlight "my paragraph," then I want the paragraph to appear as follows:

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

Thank you in advance!

Answer №1

I came across your question and discovered a helpful resource: Add tags around selected text in an element.

Below is the key code snippet that I extracted 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>

Answer №2

To achieve this functionality in JavaScript, you can utilize the surroundContents() method.

<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);
        }
    }
}

If you prefer using jQuery, you can view a demo on JSFiddle here: http://jsfiddle.net/BGKSN/24/

Source:

Answer №3

Locate the desired content and enclose it within a span tag as shown 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 №4

Great beginning, he is interested in the ability to choose text inside a div. Here is a suggestion:

HTML:

<div class="highlightText">
  This paragraph contains some text. Try selecting a part of it to see something cool happen!
</div>
<button id="makeItCool">Create Magic</button>

CSS:

.highlightText {
  margin-bottom: 2em;
}

button {
  cursor: pointer;
}

.highlight {
  background-color: blue;
}

JS:

if (!window.x) {
  x = {};
}

x.Selector = {};
x.Selector.getSelected = function() {
  var selectedText = '';
  if (window.getSelection) {
    selectedText = window.getSelection();
  } else if (document.getSelection) {
    selectedText = document.getSelection();
  } else if (document.selection) {
    selectedText = document.selection.createRange().text;
  }
  return selectedText;
}

$(document).ready(function() {
  $("#makeItCool").click(function() {
    var chosenText = x.Selector.getSelected();
    console.log(chosenText.focusNode);
    if (chosenText.focusNode.length > 0) {
      var paragraph = $(".highlightText").text();
      paragraph = paragraph.replace(chosenText, '<span class="highlight">' + chosenText + '</span>');
      $(".highlightText").html(paragraph);
    } else {

    }
  });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to eliminate space between column arrangement in Bootstrap

I've designed 3 cards containing 2 widgets each in the sidebar. To ensure responsiveness, I utilized bootstrap 4 column ordering. One problem is when the right column is larger than the left one in a row of 2 columns, there's an awkward space be ...

What is the method for obtaining the size of a mesh object in pixels (instead of Vector3) within BabylonJS?

Exploring Babylon.js How can I retrieve the size of a mesh object in pixels instead of Vector3 in a React application using Babylonjs? This is what I attempted: let meshPixelSize = meshObject.getBoundingInfo().boundingBox; ...

The submit button seems to be unresponsive despite my inputting data into the form

I am having trouble with my code to request information from a whois server and display it on my webpage. When I press Enter, everything works fine, but the Submit button is not functioning properly. The current URL of the page is: ../whois.php After hi ...

Utilizing three.js to calculate the minimum and maximum Box3 dimensions with the local

Feeling a bit stuck at the moment. I have multiple Vectors (Vertices) that are components of larger objects and I'm creating two Box3's with them: obj1box = new THREE.Box3().setFromPoints(buffer1); //buffer 1 and 2 are arrays of vectors ...

Boost the image count on Flickr by utilizing JSON data

Can we access more images from flickr? What is the default number of images? $(document).ready(function(){ $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?id=48719970@N07&lang=en-us&format=json&jsoncallback=?", function ...

The value in the input will not be refreshed

Hey there, I've been struggling to make this script work and I can't seem to pinpoint the issue. The goal is to use tinyMCE along with jQuery dialogue to take input from 2 fields and then output it in a specific format. Here's the code snipp ...

jQuery - preserving the integrity of array members when extending objects

Currently, I am in the process of developing a jQuery plugin where I'm using the common $.extend method to merge user-defined settings with default values. Here is an example: var options = $.extend({ title: '', padding: [0, 0, ...

Displaying a variety of values based on the specific URL

I am attempting to display specific values from an array of objects based on the current URL. For example, if the URL is "localhost/#/scores/javelin," I only want to display the javelin scores from my array. Here is an example of what my array looks like: ...

Express will be used to return empty values to an array

I am currently in the process of learning how to use express, so I am relatively new to it. I am facing an issue where I am trying to send data from a form I created to an array, but unfortunately, it is adding empty values to the array. The values are dis ...

Error in jQuery Ajax post request caused by a keyword in the posted data

I understand why the post is failing, but I'm at a loss on how to fix it and I haven't been able to find any solutions online. I am removing references to jEditable in an attempt to simplify things, as this issue occurs even without the jEditable ...

Activate the feature of smooth shading using Three.js

When rendering an object with textures using MTL and OBJ files in Three.js, I encountered an issue where my model was displayed with flat shading. How can I enable smooth shading? var scene = new THREE.Scene(); var mtlLoader = new THREE.MTLLoader(); mtl ...

How can union types be used correctly in a generic functional component when type 'U' is not assignable to type 'T'?

I've been researching this issue online and have found a few similar cases, but the concept of Generic convolution is causing confusion in each example. I have tried various solutions, with the most promising one being using Omit which I thought would ...

By stopping clearInterval, the setInterval operation becomes solely dependent on time

I'm new to JS/jQuery and struggling with understanding how to stop a setInterval function after a certain time interval or number of executions using clearInterval. I know this question has been asked before, but I still can't figure it out. Cur ...

Initial page fails to load on Angular application

I am currently facing an issue in my Angular app where the first page call does not load the correct route template, only displaying the menu bar. However, if I navigate to another link and then go back to the original, the correct page loads. Can anyone h ...

Avoiding the application of a border-right to the final child of a div in CSS

Check out this custom HTML code: <div class="main"> <div class="parent"> <div class="child"> <span></span> <label></label> </div> <div class="child2"> // some html content </div> ...

Influencing location preferences in Google's place search

I'm currently implementing a Google Places search feature and I need to enable "Location Biasing" for the GCC countries (UAE, Saudi Arabia, Oman, Kuwait & Bahrain). My goal is to achieve the functionality described in the following link: https://deve ...

I'm using SASS in my project, can you provide guidance on customizing the UI with @aws-amplify/ui

I've recently taken over a Next.js (React) project from another developer and they've used .scss files (SASS) for styling. The specific project I'm working on can be found here https://github.com/codebushi/nextjs-starter-dimension My task n ...

Perform a prerender of a Vue.js 2.0 component (resembling the functionality of this.$compile in Vue 1)

I'm currently working on developing reusable components specifically for gridstack. One issue I've encountered is the absence of a simple equivalent to the this.$compile method from vue 1. I came across this example that caught my attention. Her ...

Fill input text fields with values based on dropdown selection and start with 2 input fields pre-filled

Initially, the issue is that there are 2 input text fields displayed. Depending on the selection from a drop-down menu ranging from 2 to 6, additional input fields should be added or removed. Here's my code: function addElements(selectElement) { va ...

Node does not recognize the $or operator

Currently, I am enrolled in an online course and facing a problem with a query issue. Interestingly, the query functions perfectly fine in the shell, however, when executing the js file, an error arises stating: unknown operator: $or. Here is the crucial c ...