A comprehensive guide on how to find keywords within an array and then proceed to make all text within the parent div tag stand

I am currently looking for a webpage that displays a list of products based on keywords from an array. Once it detects any word in the array, it highlights it with a red background - everything is working smoothly so far. However, I now wish for the script to change the color of the entire product text (within the <div> tag) to light grey, allowing me to easily skip past that specific product when scanning through the page. Is there a way to achieve this? You can view the demo here: JSFiddle

This is the HTML code:

<div>
<p>I bought some apples.</p>
<p>Apples are £2 per kg.</p>
</div>

<hr>

<div>
<p><a href="oranges.html">I bought some oranges.</a></p>
<p>Oranges are £1.50 per kg.</p>
</div>

<hr>

<div>
<p><a href="pears.html">I bought some pears.</a></p>
<p>Pears are £1.80 per kg.</p>
</div>

And this is the JavaScript code:

var regex = /(apples|oranges)/g;

$('body a, body p').each(function() {
    var $this = $(this);
    var text = $this.text();
    if (text.match(regex) && $this.children().length===0) {
        $this.html(
            $this.html().replace(regex, '<span style="background: #fa7373;">$1</span>')
        );
    }
});

Answer №1

To change the color of specific text elements, you can use a regular expression to match the text and then apply CSS styling.

var regex = /(apples|oranges)/g;

$('body a, body p, body div').each(function() {
    var $this = $(this);
    var text = $this.text();
    if (text.match(regex)) {
        $this.css("color", "grey");
        if($this.children().length===0){
          $this.html(
              $this.html().replace(regex, '<span style="background: #fa7373;">$1</span>')
          );
        }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<p>I bought some apples.</p>
<p>Apples are £2 per kg.</p>
</div>

<hr>

<div>
<p><a href="oranges.html">I bought some oranges.</a></p>
<p>Oranges are £1.50 per kg.</p>
</div>

<hr>

<div>
<p><a href="pears.html">I bought some pears.</a></p>
<p>Pears are £1.80 per kg.</p>
</div>

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

Error encountered when trying to update Express Mongoose due to duplicate key

In my MongoDB database, I have a unique field called mail. When attempting to update a user, I encounter an issue where if I do not change the mail field, it triggers a duplicate key error. I need a solution where it is not mandatory to always modify the ...

Creating a Clickable SVG Element in React

I've been attempting to set up an onClick event in React, specifically within an SVG that includes multiple circle objects. However, when using "onClick," I'm encountering a strange issue: Upon data load, the onClick event is triggered six times ...

Transparent CSS Table Styling

Can you create a CSS effect where all content inside a table becomes transparent on hover? For example: <table><tr><td> AN IMAGE </td> <td> SOME TEXT </td></tr></table> So if either the image or the text ar ...

The AJAX request encountered an unexpected failure that cannot be identified (Using jQuery)

Are you facing issues with a service that returns JSON data? Check out this URL: If you're attempting a simple AJAX request, here's some sample code to get you started: $.ajax({ type: "get", url: "http://api.drag2droid.shamanland.com/ca ...

The positioning and floating of two divs are set to fixed without using percentage width, however, the functionality is not

Apologies for my poor English writing :) I am attempting to float two divs side by side in a fixed position, without using percentages. This code works well on most browsers but is not compatible with IE 6. HTML <div class="right"></div> < ...

Using NodeJS to retrieve the mean price from the OPSkins pricelist

Is there a way to calculate the average price of every skin listed in this document? I'm wondering how one would go about using the dates and prices in order to determine the 60-day average price. My approach would involve extracting the data from t ...

Enhancing the user experience by providing auto-complete suggestions while still maintaining the original form functionality

Encountering a curious bug that appears to be affecting only IE and Webkit browsers. I've set up a simple form as follows: <div id="output">Form output is shown here</div> <form id="myForm" action="#" method="post"> <input type= ...

Adjust the size of multiple elements upon hovering over one of them

I encountered a puzzling issue, and here is a demonstration of my problem: https://jsfiddle.net/k1y8afst/ <div class="Sample"> <div class="Dummy"> <div class="Books"> <a st ...

Choosing multiple options from a list

I am working on a messaging app where users can compose and send messages to contacts. Currently, I am only able to send messages to one contact at a time. My goal is to enable users to select multiple contacts to create group messages. Since I am new to a ...

Encountering obstacles with asynchronous requests while attempting to retrieve an Excel file using ajax

I am coding JavaScript for a SharePoint project, focusing on creating a function to retrieve data from an Excel document in a library. While I have successfully implemented the basic functionality, I am facing an issue with large file sizes causing the dat ...

Tips for displaying a loading spinner each time the material table is loading

Hey there, I'm currently working on an Angular project where I need to display a table using Material Table. To indicate that the table is loading, I've defined a variable called isLoading. Here's how it works: In my TypeScript file: @Com ...

What strategies can I use to prevent any spaces between cards when I unfold them?

Hello, I am looking to create a basic webpage. In this link, there are 4 cards that can be opened. However, when I open card B, a gap appears between card A and card C - and I'm not sure why this is happening. Here is a link to the HTML code I have us ...

What is the reason for the ul selector not functioning in the attached CSS file?

I attempted to create a navigation bar by using the code below. <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="styles.css"> </head> <body class="background"> <ul> <li>Home</li> <li>Ne ...

Styling a scrollbar with CSS3 for a container

Is there a way to customize webkit scrollbars using CSS3? I am referring to the following properties: ::-webkit-scrollbar { width: 12px; } ::-webkit-scrollbar-track { -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3); bor ...

The backdrop moving in a reverse direction

I recently made a tweak to this code that successfully moves the background in the opposite direction of the scroll. However, there is now an issue where it leaves a blank space at the top, even when the background is set to repeat. The change I made was s ...

Passing properties from the parent component to the child component in Vue3JS using TypeScript

Today marks my inaugural experience with VueJS, as we delve into a class project utilizing TypeScript. The task at hand is to transfer the attributes of the tabsData variable from the parent component (the view) to the child (the view component). Allow me ...

Issue with updating patch version using NPM standard-version

I have integrated standard-version into my javascript project. I made sure to include the release script in my package.json: "scripts": { ... "release": "standard-version" } However, after adding a commit with the mes ...

Setting the title attribute for option elements in a select element that is bound to a model using AngularJs

I'm currently working on an HTML select element that is connected to an ng-model. Here's what the setup looks like: <select data-ng-model="accountType" data-ng-options="at.name for at in accountTypes"></select> This is how my accou ...

Integrating data binding within a .append function using AngularJS

I followed this code example (http://jsfiddle.net/ftfish/KyEr3/) to develop a form. However, I encountered an issue with an input having ng-model set to "value" and needing to display that value within {{ }} in a TD: angular.element(document.getElementByI ...

Guide on utilizing protractor to confirm equality of two spans in varying positions?

<span ng-bind="locations.selectedCount" class="ng-binding">1005</span> <span ng-bind="locations.selectedCount" class="ng-binding">1005</span> What method can I use in Protractor to verify that the values of these two spans are ide ...