Highlight a pair of words in a phrase using jquery technology

Only one word in my code is highlighted

$(document).ready(function() {
  let firstword = 'web';
  let secondword = 'js';

  $(".field.ConditionsAccept>.caption:contains('" + secondword + "'):contains('" + firstword + "')").each(function() {
    var regex = new RegExp("(" + secondword + ")", 'g');
    var regex2 = new RegExp("(" + firstword + ")", 'g');
    $(this).html($(this).text().replace(regex, '<span class="word" style="text-decoration: underline">$1</span>'));
    $(this).html($(this).text().replace(regex2, '<span class="word2" style="text-decoration: underline">$1</span>'));
  });
});
.ConditionsAccept { width: 500px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="field ConditionsAccept">
  <caption class="caption">Here is some web and js stuff</caption>
</table>

Answer №1

The second $(this).text() function has removed the first span from the content

Changing the HTML twice is not recommended, especially if the initial text contains words like span, word, or decoration, as it may corrupt the first span during the second alteration.

To ensure safety, it is best to replace all text before modifying the HTML content.

$(document).ready(function() {
  let primaryWord = 'web';
  let secondaryWord = 'js';

  $(".field.ConditionsAccept>.caption:contains('" + secondaryWord + "'):contains('" + primaryWord + "')").each(function() {
    const regex  = new RegExp("(" + secondaryWord + ")", 'g');
    const regex2 = new RegExp("(" + primaryWord +  ")", 'g');
    let text = $(this).text()
    console.log(text)
    text = text
      .replace(regex,  '<span class="word"  style="text-decoration: underline">$1</span>')
      .replace(regex2, '<span class="word2" style="text-decoration: underline">$1</span>');
    $(this).html(text)
      
  });
});
.ConditionsAccept { width: 500px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="field ConditionsAccept">
  <caption class="caption">Here is some web and js stuff</caption>
</table>

Answer №2

An issue arises when the text() function is used to retrieve the content of an element, as it only fetches the text and strips away the HTML markup. This causes a problem where the first use successfully replaces the word 'js', but on the second use, it removes the span element along with it, leaving only the replacement of the word (which is defined as 'firstword' in the regex) during the second occurrence.

To address this, the code snippet opts for using the html() function instead of text() to ensure that the span element is retained.

<div class="field ConditionsAccept">
  <div class="caption">text0 js text web text1 js text3</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
  $(document).ready(function() {
    let firstword = 'web';
    let secondword = 'js';
    $(".field.ConditionsAccept>.caption:contains('" + secondword + "'):contains('" + firstword + "')").each(function() {
      var regex = new RegExp("(" + secondword + ")", 'g');
      var regex2 = new RegExp("(" + firstword + ")", 'g');
      $(this).html($(this).html().replace(regex, '<span class="word" style="text-decoration: underline">$1</span>'));
      $(this).html($(this).html().replace(regex2, '<span class="word2" style="text-decoration: underline">$1</span>'));
    });
  });
</script>

Answer №3

I tested out the code you provided and encountered the same issue mentioned earlier. To resolve it, I made the following adjustments:

            $(this).html($(this).html().replace(regex, '<span class="word" style="text-decoration: underline">$1</span>'));
            $(this).html($(this).html().replace(regex2, '<span class="word2" style="text-decoration: underline">$1</span>'));

This solution worked for me. Feel free to give it a try.

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

Challenges encountered while creating a Number Tables Program (such as displaying 12 x 1 = 12) using Javascript

Currently, I am working on developing a program that can generate mathematical tables for any given number. For example: 3 x 1 = 3 3 x 2 = 6 3 x 3 = 9 3 x 4 = 12 To achieve this, the user should provide the following inputs: (1) The number they want ...

Guide to dynamically insert rows in HTML using Vue.js based on the selected option

This is the initial row. Depending on the selection made here, different rows will be displayed <div class="row"> <div class="col-md-4"> <div class="form-group label-floating"> <label class="control-label">Case Type< ...

Explore the capabilities of Vue.js by creating multiple JavaScript classes within your application

<div class="container" :class="{ qwerty: !open }" :class="lower? 'left' : 'right'"> Hey there, I've noticed that Vue seems to only allow me to add one class with conditions, as shown in the exam ...

Tips for avoiding automatic updates to .js scripts after pressing F5

Is there a method to stop a JavaScript script from resetting when the user refreshes the page? For instance, if I have a picture slider that is constantly changing images, I would like the script to continue where it left off instead of starting over wit ...

Tips for organizing data and dynamically linking options to another select value?

One of my challenges involves working with two select elements. The first select allows for multiple options, while the second select is dependent on the choice made in the first one. <select class="form-control" id="select1"> <option value=""& ...

Trigger Ajax only when a new row is added by the user in the SQL database using PHP Codeigniter

Avoiding frequent AJAX calls is necessary to prevent slowing down the POS system. We now prefer to trigger AJAX only when a user enters data from the frontend site, such as adding items to the cart. This helps in keeping the POS processes running smoothly ...

Prevent the onClick event from being triggered by utilizing JSON data

I am trying to implement a feature where a button click is disabled based on a parameter fetched from a JSON file: JSON Parameter "reactJson": { "disable:"true" } Currently, my onClick method is functioning correctly. However, ...

Issue with Jquery Slider Showing Empty Slide

Currently addressing issues with the slider on my site, which utilizes SlidesJS at . There seems to be a problem where it shows a blank slide inexplicably. After investigating, I noticed that a list element is being added to the pagination class, but I can ...

Trouble with using AJAX to transfer a JavaScript variable to a PHP file

I need assistance in sending a JavaScript variable to a PHP file for displaying comments on a webpage. While I have successfully sent the JS variable to other PHP files, I'm facing issues when trying to do the same with the comment-list.php file. It ...

Calculate the height of the document in Python by using the function $(document).height()

I am looking to retrieve the height of a document for different URLs, essentially creating a JavaScript function similar to $(document).height() that works across all pages. Any suggestions on how I can accomplish this task? I have experience with Python ...

Stretch a component outside of the bootstrap container

Currently, I am working on a mockup using Bootstrap 4 and have encountered an unusual element inside the container where the background extends beyond the container. I'm not sure how to address this issue effectively. I attempted to use position: abso ...

Changes on services do not affect the Angular component

Currently facing an issue with my Angular assignment where changing an element's value doesn't reflect in the browser, even though the change is logged in the console. The task involves toggling the status of a member from active to inactive and ...

Unable to retrieve data. Issue: Unable to send headers after they have already been sent to the client

Experiencing an error while attempting to retrieve posts from a specific user. The code for fetching the data appears to be correct, so it's unclear where the error is originating from. Error from server side https://i.stack.imgur.com/ep1Xh.png Error ...

Anticipating the completion of a process.nextTick cycle

Problem Statement I am currently working on a Node.js application that involves complex calculations and utilizes recursive algorithms. The code snippet below gives a brief overview of how the calculations are performed: // routes.js - express.js routes ...

Creating Filled DIVs using JavaScript

Although it may appear to be a common inquiry, my specific needs have not been addressed in any of the Stack threads I've come across. I am dealing with a series of nested DIV statements, as demonstrated here (not all CSS included). I am looking to ...

What is the necessity of utilizing getStaticPaths() alongside getStaticProps()?

When working with dynamic routes, such as [id].js, the static pages generated using npm run build will result in an [id].html page. Any route containing /something will display "Hello World". However, when we dynamically generate content on the page by ut ...

Tabulator and its convenient scrollable column feature allows for easy navigation

In case my tabulator column is exceeding its length, is there a way to enable scroll functionality for that specific column? Although the resizable rows feature permits users to resize and view all the content, can a scrollbar be implemented exclusively ...

Exploring GatsbyJs: Optimal Strategies for Storing Strings and Text on Static Websites

Currently in the process of building a website using Gatsby JS and Material UI. I'm wondering about the best approach for storing the site content. This website will serve as a promotional platform for a small business. Should I store the text direct ...

Tips on adjusting the hover color in the data grid

I want to adjust the color of the Datagrid when hovering over it, does anyone know how to do this? The default color displayed is light blue, but I would like to change it to a different color. Can someone please assist me with this? Looking for document ...

Typescript and Mongoose Schema - Common Design Mistakes

I am encountering two issues while defining a schema using mongoose and typescript. Below is the code snippet I'm having trouble with: import { Document, Schema, Model, model} from "mongoose"; export interface IApplication { id: number; name ...