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

"Enhance User Experience with a Bootstrap Dropdown Button Offering Block Level Function

I'm attempting to modify a bootstrap 3 dropdown button to fully utilize the width properties of .btn-block class. It appears that the dropdown button does not respond in the same way as regular buttons. Below is my current code: <div class="row"&g ...

Transform a JSON array with keys and values into a structured tabular format in JSON

Looking to transform the JSON data below for a Chart into a format suitable for an HTML table: var chartJson = [ { header : '2016', values : [1, 5, 9] }, { header : '2017', values : [2, 4, 8] ...

Element not found: {"method":"name","selector":"markUp"}

Snippet : System.setProperty("webdriver.chrome.driver", "C:\\Users\\pkshirs3\\SeleniumMaterial\\chromedriver.exe"); WebDriver webDriver = new ChromeDriver(); String urlToBeUsed = "internalURL"; webDri ...

Initiating a animation prior to the execution of JQuery's load() function

I'm currently exploring the functionalities of JQuery's load() function and I am puzzled as to why a particular animation does not occur prior to the load request. For instance, when I include a script like this: $('#clickme').click(f ...

Executing a click on a checkbox element in Python with Selenium

Background: Currently, I am in the process of developing a Python script that will automatically download listings from a specific website. I have successfully programmed the script to navigate the webpage, search for keywords, click on the search button, ...

The server mistakenly sent the resource as a Stylesheet even though it was interpreted differently

Dear Fellow Coders, Could anyone lend a hand? I encountered this issue on my website after uploading it to my FTP: "Resource interpreted as Stylesheet but transferred with MIME type text/plain" </head> <body> <div class= "navbar navbar ...

A Node.js feature that enables atomic file replacement, triggering watchers only once

I have a unique scenario where I need to handle two types of processes. One process is responsible for writing a file, while the other processes are required to read it whenever there is a change. In my research, I came across fs.watch as a solution to ke ...

Automatically filling in options in a drop-down menu based on the selection made

I'm working with MySQL tables that have this structure: regions table id | region ------------------- 1 | Region1 2 | Region2 ... and schools table id | school ------------------- 1 | schno1 1 | schno5 1 ...

What is causing the action button in my MUI snackbar to occupy an additional line?

I'm currently learning how to use MUI and I'm struggling with a specific issue. The close button in my code is appearing on a separate line, but I want it to be on the same line as the word "again". I've tried experimenting with absolute pos ...

Typescript is throwing a Mongoose error stating that the Schema has not been registered for the model

I've dedicated a lot of time to researching online, but I can't seem to figure out what's missing in this case. Any help would be greatly appreciated! Permission.ts (This is the Permission model file. It has references with the Module model ...

Is there a way to prevent fancybox from automatically opening when the page loads?

I'm puzzled by the behavior of this jQuery code that causes a fancybox image to open automatically when the page loads instead of waiting for user interaction. Can someone show me how to modify it so that the image opens only when clicked on? Check ou ...

How can one guide a glTF model in the direction it is pointed using A-frame?

I have a 3D model of my customized robot loaded in an A-frame scene using version 1.0.4. Currently, I am able to rotate the robot along its x, y, z axes, but I am facing an issue where it continues to move in its original direction rather than the one it i ...

What is the best way to shorten string values that exceed a certain length?

Here is an array list I have: $myarray = array( array( 'name' => 'File name 1 - type.zip', 'size' => '600KB', ), array( 'name' => 'File name 2 - type.pdf&a ...

Is there a way to streamline this function call that appears to be redundantly repeating the same actions?

I have developed a function to search for blog posts, prioritizing titles over excerpts and excerpts over content when added to the containsQuery array. While the code seems to be working well, I have noticed that there is a lot of redundant code. How can ...

Dealing with a variety of AJAX requests

After implementing AJAX to retrieve JSON data from multiple URLs and store them in separate arrays, I encountered an unexpected issue. Take a look at the code snippet below: var var1 = $.ajax({ url: FEED1, dataType: 'jsonp', crossDom ...

The Javascript function is being called, yet it cannot be defined

I am currently in the process of revamping an older website that was originally designed for compatibility with IE8 and utilizes framesets for layout management. As part of this update, I am trying to implement a piece of code within one frame that will g ...

Is there a way to align the image to the left within the div contained in my header section?

I am facing an issue with positioning the logo in the header section of my website. It appears correctly on the left side for tablet and mobile versions, but on desktop, it does not align to the corner as desired. I tried adding a right margin, but I belie ...

The issue of CSS3 Grid-gap not functioning properly on iPhone devices

I've been working on creating a CSS template and everything seems to be functioning correctly, except for the grid gap which doesn't seem to work properly on my iPhone. Here's the code I have so far: <div class="grid"> <h1 ...

Is there a quicker method than using document.getElementById('element-id').innerHTML to retrieve content?

Currently, I am developing a user-friendly step-by-step wizard for my website to gather information about custom orders. Utilizing JavaScript, I have been tasked with updating the content of each "page" using the document.getElementById('element-id&ap ...

Encountering issue with Django locating static file (1.5) showing ERROR 404 code 1649

I'm facing some difficulties in setting up my local Django site. I've reviewed the previous questions and answers, but haven't been able to find a solution. [20/Oct/2013 03:56:33] "GET /rides/ HTTP/1.1" 200 230 [20/Oct/2013 03:56:33] "GET / ...