"Enhancing text by highlighting specific words and enclosing them in a new element with a data attribute – a simple guide

JSFIDDLE

HTML:

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris sit amet est tempus, fermentum ligula et, hendrerit nisl. Praesent tempor eget quam quis auctor. Vivamus mollis mauris id sem aliquam, vel fermentum neque fringilla. Morbi malesuada accumsan augue ut hendrerit. Aenean commodo vulputate lacinia. Integer at purus eget arcu venenatis consectetur vel sed sem. Mauris quis est id ligula aliquam tempor a nec neque. Donec scelerisque velit ac metus aliquet, in euismod nisl lacinia. Quisque imperdiet gravida facilisis. In hac habitasse platea dictumst. Quisque vel erat congue, consequat libero eget, blandit sapien. Suspendisse potenti. Praesent at mollis purus.</p>

CSS:

.highlight {
  color: red;
}

JS:

$(function(){
    
  $('p').click(function(){
    // get highlighted words
    
    // get user input
    var user_input = window.prompt();
    
    // put highlighted words in <span class="highlight"></span> element
    // and add data-id to the span element
    // expected output:
    // <p>... <span class="highlight" data-id="user input here">highlighted words here</span> ...</p>
  });
  
});

I have content in a p tag with specific requirements for highlighting:

  1. User selects a word or phrase within the text
  2. User is prompted to enter additional information
  3. The selected words are wrapped in a span tag with a custom attribute (data-id) populated by the user's input from the prompt

How can I implement this functionality?

Answer №1

Expanding on the concepts discussed in this forum post to fit your specific scenario

function selectHTML() {
    try {
        if (window.ActiveXObject) {
            var selection = document.selection.createRange();
            return selection.htmlText;
        }
    
        var newElement = document.createElement("span");
        var range = getSelection().getRangeAt(0);
        range.surroundContents(newElement);
        return newElement.innerHTML;
    } catch (error) {
        if (window.ActiveXObject) {
            return document.selection.createRange();
        } else {
            return getSelection();
        }
    }
}

$(function() {
    $('#changeColor').click( function() {
        var value = prompt("Enter a value");
        var selectedContent = selectHTML();
        $('span').addClass('highlight').attr('data-id',value);
    });
});
.highlight{
color:red;  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris sit amet est tempus, fermentum ligula et, hendrerit nisl. Praesent tempor eget quam quis auctor. Vivamus mollis mauris id sem aliquam, vel fermentum neque fringilla. Morbi malesuada accumsan augue ut hendrerit. Aenean commodo vulputate lacinia. Integer at purus eget arcu venenatis consectetur vel sed sem. Mauris quis est id ligula aliquam tempor a nec neque. Donec scelerisque velit ac metus aliquet, in euismod nisl lacinia. Quisque imperdiet gravida facilisis. In hac habitasse platea dictumst. Quisque vel erat congue, consequat libero eget, blandit sapien. Suspendisse potenti. Praesent at mollis purus.</p>
<input id="changeColor" type="button" value="Select text and Change Style" />

Answer №2

If you utilize the JSFiddle provided in the comment, you can accomplish it as shown below:

function selectHTML() {
  try {
    if (window.ActiveXObject) {
      var c = document.selection.createRange();
      return c.htmlText;
    }

    var nNd = document.createElement("span");
    var w = getSelection().getRangeAt(0);
    w.surroundContents(nNd);
    return nNd.innerHTML;
  } catch (e) {
    if (window.ActiveXObject) {
      return document.selection.createRange();
    } else {
      return getSelection();
    }
  }
}

$(function() {
  $('p').click(function() {
    var selected = selectHTML();
    var user_input = window.prompt();
    $('span').addClass('highlight').attr('data-id', user_input);
  });
});
.highlight {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris sit amet est tempus, fermentum ligula et, hendrerit nisl. Praesent tempor eget quam quis auctor. Vivamus mollis mauris id sem aliquam, vel fermentum neque fringilla. Morbi malesuada accumsan
  augue ut hendrerit. Aenean commodo vulputate lacinia. Integer at purus eget arcu venenatis consectetur vel sed sem. Mauris quis est id ligula aliquam tempor a nec neque. Donec scelerisque velit ac metus aliquet, in euismod nisl lacinia. Quisque imperdiet
  gravida facilisis. In hac habitasse platea dictumst. Quisque vel erat congue, consequat libero eget, blandit sapien. Suspendisse potenti. Praesent at mollis purus.</p>

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

The textbox fails to update when the condition in the IF statement is met

In the following code, I have an input box with the ID volumetric_weight that gets updated on keyup. However, the second textbox with the ID volumetric_price does not update as expected, even though I believe I wrote it correctly. I am wondering if there ...

Acquiring HTML form data using JavaScript

Although it may seem trivial, I'm facing a challenge. I have an HTML form that is dynamically generated by JavaScript and populated with initial data fetched from the server. The form is displayed correctly with the pre-filled data. My goal is to allo ...

Launch a facebox for a PHP form action and hyperlink

Can anyone guide me on how to open this in a facebox using PHP functions? echo "< font class=text16bu-ongreen>&nbsp;".lang("Add Payment")."&nbsp;< /font>< br>< br>"; if ($balance > 0) { reset($paymentplugins); while ( ...

"Click here to access the downloadable content obtained through web scraping

I am looking to automate a task using Python where I need to get a PDF file from a website with fileid 8426 and date 03312021. Visit this link: Click on the "Download PDF" button Save the downloaded file to a directory After exploring, I came across a P ...

Is the mobile site displaying CSS pixels in the physical pixel resolution?

I am struggling to grasp the problem and finding it challenging to explain it clearly, so I have attached a picture depicting the issue. https://i.stack.imgur.com/E9Gzj.png My current approach involves using ratios of 100% and 100vw for element widths. D ...

Guide to sending DevExtreme data grids to ASP.NET MVC controllers

Currently, I am utilizing a datagrid with DevExtreme. I am wondering how I can pass the datagrid to my controller in ASP.NET MVC. In my view, I have attempted the following: @using (Html.BeginForm("action-name", "controller-name", FormMethod.Post)) { ...

html - Link not clickable inside accordion header

I am encountering an issue with my accordion that has links in the header. Currently, the accordion opens when clicking anywhere on the header, including the link itself. This unintended behavior prevents users from being redirected to the link (href) when ...

What is the best way to create a screen capture of a webpage using a URL?

Currently working on a Spring MVC website project, I have implemented a form requesting the user's website URL. Once entered, I aim to display a screenshot of the specified website for the user to view. Contemplating whether to generate the image on ...

Using react-router, learn how to access the element ID to display all data from the clicked element

Currently, my component displays all the products. However, I want to enhance it by creating a functionality where clicking on a product opens a component that shows all the data related to that specific product. Upon clicking, the url shown is http://loca ...

"Utilizing jQuery to integrate an Ajax-powered Gauge using Google Visualization API

I need help creating a dynamic dashboard gauge that updates using ajax. The code snippet below shows what I have so far, but I'm struggling with updating the gauge itself. Any advice or suggestions on how to achieve this? google.load('v ...

Achieving optimal functionality of @media queries when using buttons

My goal here is to achieve the following: Make these buttons responsive on all screen sizes Ensure that the buttons shift down when the screen size reaches Mobile size or smaller, while maintaining at least 4 buttons per row for future additions When the ...

Error: Unable to access the 'TigerNo' property of an undefined object. Setting tempObj['TigerNo'] to the default TigerNo value from the sports record

I need some help with JavaScript programming. Although I am able to retrieve values in sportsRecord, I am encountering difficulties assigning them to tempObj['TigerNo']. Whenever I try to assign the value, I encounter the following error message ...

Improving the way text entered in an input box is displayed using HTML table cells

Seeking advice on how to display the last two input boxes in a dynamic HTML table so that users can easily view the data they have entered. The issue arises when the length of the data in these columns is large, making it difficult for users to see all the ...

The resetting of checkboxes in the Boostrap form validation form is not functioning properly

I am currently working on form validation using Bootstrap. Although resetForm(); is functioning properly, I am facing an issue with resetting the checkbox upon form submission. I have attempted methods like $('.form-check-input').val();, $(' ...

What causes AngularJS to generate an error when attempting to construct a URL for the src attribute of an iframe?

Recently, I've been working with AngularJS directives and encountered an issue while trying to use an expression in the src attribute of an iframe. The error message I received referenced a URL that didn't provide much insight: http://errors.ang ...

Formik introduces a fresh Collection of values rather than just appending a single value

Currently, I am working on a form that utilizes cards for user selection. The form is built using the useFormik hook along with yup for validation purposes. Below is an example of the code structure: In the file form.tsx, we have: export const validationS ...

Issue with Bootstrap 4 Carousel Indicators Not Updating Active State Properly

I set up a Bootstrap Carousel and intentionally left the carousel-indicators section blank so that it could be dynamically populated with jQuery based on the number of slides. <section class="carousel-banner side-by-side darkblue-background-color&q ...

Ways to track the visit data for different languages in Google Analytics when the language is not included in the URL

On my website, I track Google Analytics by adding the tracking code to the header. The standard implementation of GA tracking is as follows: ga('create', 'UA-483951-1', 'auto'); ga('send', 'page ...

Locating a specific value from an href using BeautifulSoup and regular expressions

I am working with the code below and need to extract the value at the end of the href. Is there a way to use BeautifulSoup/Regex to extract the href and find values after page=? from bs4 import BeautifulSoup import requests import json import re request ...

javascript is failing to display the appropriate message at the correct moment

Wrote a code to handle the type of message I should get, looping over all the rows in the table to find matching conditions. These are my conditions: - If all rows have data-mode="success" and data-pure="yes", it's correct and successful. - If any row ...