How can you locate and emphasize specific text within various elements using JavaScript?

Created a script to highlight linked text in another HTML page.

 <p>Click <span class="f1"><a href="#myModal" data-reveal-id="myModal">here</a>/span></p>

    <div class="leftspread">
    <p class="table-caption"><span>CHAPTER 4: Vocabulary Checklist</span></p>
    <div id="myModal" class="reveal-modal" ><span style="float:right;"><a class="close-reveal-modal" style="font-size:1.5em;">&#215;</a></span> 
    <div class="voca-head tspace"><strong>CHAPTER 4: Vocabulary Checklist</strong></div>
    <div class="voca">&#x00A0;</div>
    <div class="voca"><a href="page012.xhtml#pg012">business process re-engineering (n)</a></div>
    <div class="voca"><a href="page012.xhtml#pg012">business process</a></div>
    <div class="voca"><a href="page016.xhtml#pg016">business-to-employee (B2E) (n)</a></div>
    <div class="voca"><a href="page033.xhtml#pg033">corporate social responsibility (n)</a></div>
    <div class="voca"><a href="page022.xhtml#pg022">discretion (n), discreet (adj), discretionary (adj)</a></div>
    </div>
    </div>

<script type="text/javascript">
$(document).ready(function(){
    $(document).scrollTop(0);
});
radioBtn();
</script>

The list of keywords (coded above in leftspread) will display as a popup when the text here is clicked.

https://i.sstatic.net/6lKAx.jpg

In the page012.xhtml:

CSS:

.highlight{
    background:yellow;
}

HTML:

<p><span class="glossary">business process re-engineering</span></span></p>

<p><span class="glossary">business process</span></span></p>

Script:

    <script>    
    $(document).ready(function(){
    //alert( window.location.href.split("#")[1] );
    var currentURLString = window.location.href.split("#")[1];
    //currentURLString = currentURLString

    //alert(currentURLString)

    if(currentURLString != undefined){
    $(".glossary").addClass('highlight');       
    }

    //alert(currentURLString);


    });
    </script>

It works correctly, but all the text highlighted in yellow wherever <span class="glossary"> is defined, not just the clicked word.

https://i.sstatic.net/M5unG.png

However, I need to only highlight the specific word that is clicked from an anchor tag and ignore any surrounding coded words without classes.

<span class="glossary">business pro</span><span class="ls30 lm42 glossary">cess re&#57394;eng</span></span>

This means only the clicked word should be highlighted, not any other adjacent text coded without classes.

<span class="ls1 lm41">ation of <span class="f1 s2">business pro</span><span class="ls30 lm42">cess re&#57394;eng</span></span><span class="ls31 lm43">ineering </span></span>

If anyone could please fix and resolve this issue, it would be greatly appreciated.

Answer №1

What is the reason behind choosing page number #pg012 within fragment

<a href="page012.xhtml#pg012">
?
You have the option to directly reference the entire text you wish to emphasize
#business process re-engineering (n)
on a different page.

<a href="page012.html#business process re-engineering (n)">business process re-engineering (n)</a>

JS code snippet:

$(document).ready(function () {
  var currentURLString = window.location.href.split("#")[1];
  $("#page012:contains('" + currentURLString + "')").html(function (_, html) {
    var regex = new RegExp("/" + currentURLString + "/g");

    var re = new RegExp(RegExp.escape(currentURLString), "g");
    return html.replace(re, '<span class="highlight">' + currentURLString + '</span>')
  });

});

RegExp.escape = function (text) {
  return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};

I have set up a similar example on Plunker. I trust this explanation helps!!

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 implement the CSS on images with an ID such as img120 within a div that has a class of 'open'

<div class='cluster' id='12' 'style='width:350px;min-height:150px;border:4px solid #339966;'> <div class='image' style='width:150px;height:150px;border:2px solid black;float:left;margin-bottom: ...

In what ways can the current theme be utilized to optimize spacing?

Greetings everyone, I need assistance with adding margins above and below a Button element. Below is the relevant code snippet: const useStyles = makeStyles(() => ({ progress: { display: 'block', margin: 'auto', }, })); ...

`Using top-level await in a module can interfere with the firing of the `onload` event

It seems that the load event is not triggering when I use await for an IndexedDB opening at the top level within an indirectly loaded module. Interestingly, if I remove the await, the load handler works as expected. Similarly, replacing the openDB call wi ...

In order to work with the optionSelectionChanges property of the MdSelect directive in Angular Material2, it

Within my application, there is a Material2 select dropdown widget containing several options. app.component.html <md-select placeholder="Choose an option" [(ngModel)]="myOption" (optionSelectionChanges)="setOptionValue(myOption)"> &l ...

I'm attempting to pass an array to the ajax load function, but for some reason my controller is not receiving the array correctly

Here is the JQuery code snippet: $(function () { $('#dish-filter-form').on("submit", function (e) { e.preventDefault(); var dishName = encodeURIComponent($('#dishName').val()); var selectFoodType = encodeUR ...

The minification of HTML scripts may cause problems with the <script> tag

Greetings! I have a PHP script that is used to minify the page by removing any comments or spaces. Here is the script: <?php function sanitize_output($buffer) { $search = array( '/\>[^\S ]+/s', '/[^&b ...

Changing the order of a list in TypeScript according to a property called 'rank'

I am currently working on a function to rearrange a list based on their rank property. Let's consider the following example: (my object also contains other properties) var array=[ {id:1,rank:2}, {id:18,rank:1}, {id:53,rank:3}, {id:3,rank:5}, {id:19,r ...

Error when redirecting in Express due to invalid integer input syntax

After executing a PUT query in Postgres through Express, I encountered the following error message: Error: invalid input syntax for integer: "all-calls" This issue seems to be related to the line of code within the router.put function that says response. ...

HTML content that is produced through JSONP retrieval

Recently, I've been experimenting with the jQuery library and have found it to be quite useful. Lately, I've been delving into AJAX requests to fetch various information like weather updates, current downloads, and more, which has been going smoo ...

List organized in two columns utilizing the data-* attribute

Is it possible to display a list in a two-column format based on a data attribute of each item? <ul> <li data-list="general_results">general text1</li> <li data-list="general_results">general text2</li> <li dat ...

Issue encountered while presenting canvas on HTML due to Firebase information

Even though I believe I'm following the correct steps, I am facing an issue where the graph displaying real-time database values is not showing up. The first image shows my real-time database and a demostration as shown in images 2 and 3. While the da ...

How come the sound is played after the command is given?

function myTimer() { randint= Math.floor(Math.random() * 10)+1; randstimuli=gorilla.stimuliURL(dict[randint]); var audio = new Audio(randstimuli); audio.play(); var start=Date.now(); var ans=prompt("was the last number the same as t ...

JSONP version of the JQuery method for loading content

I am currently developing a web page widget for my organization. The goal of this widget is to inject an HTML snippet from any domain (including our website or a customer's CNAME) into the customer's website, which could be hosted on various plat ...

The toggler in Bootstrap 5's Navbar menu is experiencing difficulties opening on mobile browsers

Just arrived here for the first time. Encountering an issue with my Bootstrap 5.1 Navbar menu. Background info: My website is hosted locally via Xampp with php pages for forms and cookies. Everything functions perfectly on desktop. Checked responsiveness o ...

How can we improve our vertical division method?

Looking for a more efficient way to create a vertical divider between two divs. I want the divider to be centered between the "why choose" and "gallery" sections. Here is an example of what I'm trying to achieve. I've attempted the following co ...

The text is exceeding the boundaries of its container, displaying in a single line that extends beyond the page

I am currently working on incorporating text into the project-details section by utilizing a rich text uploading field in Django admin. Despite inputting the text as a paragraph in the Django admin project description, it displays as a single line that ove ...

Regular expressions or regex can be used to match the initial letter or letters of various words

Struggling with regex? After searching for an hour, the best solution found was this one. Still unable to crack it though... Here's what I need: Have a JS array that needs to be filtered. The array looks like: [ 'Gurken halbiert 2kg', &a ...

How can I assign a unique background color to each individual column within a RadioButtonList?

I have an issue with setting 3 repeated columns. I want to assign different background colors to each of them. If you have any ideas on how I can achieve this, please share. Here is the code for my RadioButtonList: <asp:RadioButtonList ID="rblTimeSlot ...

A guide on extracting the current website URL in a React application

I wanted to find a method to duplicate the text from a URL so that users could easily share the link with others. ...

How can a Chrome extension transfer an ArrayBuffer or Blob from a content script to the background script without compromising its data type?

In my current script, I am downloading binary data using XHR in the content script and sending it to the background script: let me = this; let xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.responseType = 'arraybuffer'; xhr.onlo ...