Using jQuery to locate text and apply a specific class

Explaining My HTML Structure:

<div id="test-listing">
<article>
<a>Some URL</a><h3>Some Text</h3>
<p>Drink this coffee</p>
</article>
<article><a>Some URL</a><h3>Some Text</h3><p>Drink this Coffee</p></article>
<article><a>Some URL</a><h3>Some Text</h3><p>Drink this Coffeeland</p></article>
<article><a>Some URL</a><h3>Some Text</h3><p>Drink this coffees</p></article>
</div>

Examining My CSS Class:

.hit-list {
    background: none repeat scroll 0 0 rgba(255, 0, 0, 0.1);
    border-bottom: 1px solid #FF0000;
}

I am tasked with searching for the term coffee without regard to case sensitivity within the text. It's important to note that variations like coffees, Coffee, Coffeeland should also be considered and have a specific class applied. The adjusted code would look like this:

<div id="test-listing">
      <article><a>Some URL</a><h3>Some Text</h3
       <p>Drink this <span class="hit-list">coffee</span></p>
      </article>
      <article><a>Some URL</a><h3>Some Text</h3
       <p>Drink this <span class="hit-list">Coffee</span></p>
      </article>
      <article><a>Some URL</a><h3>Some Text</h3
       <p>Drink this <span class="hit-list">Coffee</span>land</p>
      </article>
      <article><a>Some URL</a><h3>Some Text</h3
       <p>Drink this <span class="hit-list">coffee</span>s</p>
      </article>  
    </div>

I've researched similar posts but haven't come across anything that fits my specific requirements of working within a loop structure. Additionally, I'm not interested in using a jQuery plugin to accomplish this task.

Thank you.

Answer №1

Here's a method you can use:

$('div#test-listing article').html(function () {
    return $(this).html().replace(/coffee(?=[^>]*<)/ig, "<span class='hit-list'>$&</span>");
});

If your search term changes dynamically, try this approach:

var searchTerm = 'coffee';
$('div#test-listing article').html(function () { 
    return $(this).html().replace(new RegExp(searchTerm + "(?=[^>]*<)","ig"), "<span class='hit-list'>$&</span>");
});

See Updated Demo

Answer №2

Make sure to assign a class "article" to the article element

<div id="test-listing">
<article class="article">
<a>Some URL</a><h3>Some Text</h3>
<p>Drink this coffee</p>
</article class="article">
<article class="article"><a>Some URL</a><h3>Some Text</h3><p>Drink this Coffee</p></article>
<article class="article"><a>Some URL</a><h3>Some Text</h3><p>Drink this Coffeeland</p></article>
<article class="article"a>Some URL</a><h3>Some Text</h3><p>Drink this coffees</p></article>
</div>

Then use the following code

$('#test-listing').find('.article').each(function ( i , val) {

// This will replace all instances of coffee or Coffee with the specified html tag
console.log($(this).text().replace(/Coffee|coffee/g, "<span class='hit-list'>Coffee</span>")); 

});

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

Having issues with Angular Material, specifically with mat-list-item and routerLinkActive not functioning as expected

Currently, I am working with a navigation view that utilizes the MatSidenavModule. The issue I am encountering is on mobile screens. When I click a mat-list-item, the mat-sidenav closes as expected. However, upon opening the mat-sidenav again, Material alw ...

jQuery rounded images slideshow

Currently, I am working on developing a jquery slider that showcases rounded images. Below is the HTML code: jQuery(document).ready(function($) { var $lis = $('ul').find('li'), length = $lis.length; $lis.each(function( ...

Guidance on Configuring Django Static Files

For setting up my Django static files, I added the following code to settings.py: STATIC_URL = '/static/' STATIC_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') To implement this ...

Creating a CSS grid layout with an unspecified number of columns all set to equal width

Currently, I am in the process of designing a navigation bar using grids. In essence, when the user is an admin, there should be two additional links at the end of the bar. These links need to have the same width and should not be affected by the amount of ...

Retrieve all chosen option elements from every select element within a form

Hello everyone and thank you for offering your assistance in answering my query. I am currently working on a form that includes 6 select elements all having the "skillLevel" class. I am looking to extract the values of each select element, preferably in a ...

Ensuring that your content expands to fit the sidebar dimensions

I have diligently searched for a solution to my issue both on Google and here, but have yet to find one that works. I've experimented with various CSS properties like display: table-cell and inline-block, as well as different overflow options, but not ...

What is the highest possible z-index value that can be applied in

Is there a specific limit to the CSS property z-index? Are there variations in accepted values among different browsers? How do browsers typically handle extreme z-index values? I recall reading about a potential maximum value for z-index somewhere, but I ...

I encountered an issue where I was unable to customize the styling of the

I'm facing an issue where I cannot override the style using `className` on a `Button`. Interestingly, the same style works correctly on a `TextField`. However, when I use the `style` prop, it allows me to successfully override the `Button` style. What ...

Exclusively Bootstrap-Timepicker

Is there a way to create a textbox with a time picker only? I am looking for guidance on how to do this using the following example: http://jsfiddle.net/RR4hw/11/ jQuery("#startDate").on("dp.change",function (e) { jQuery('#endDate').data("DateTi ...

Determine the position of the cursor in an editable span

Is there a way to add text at the cursor position in an editable span when a button is clicked? The span contains multiple lines of text and HTML tags. [Take a look at this example on JSFiddle](http://jsfiddle.net/8txz9sjs/) ...

Modify the color of the menu in OpenCart 1.5.6.4 to give it a fresh

In the default theme of OpenCart 1.5.6.4, I am looking to change the background color of the dropdown menu which is currently defined by the background image 'menu.png' to a custom hex value. The CSS code for this section is shown below: #menu & ...

I encountered an issue where the font awesome icons failed to load on my website

My website is experiencing an issue where all the Font Awesome icons are not displaying despite having added Font Awesome. Here is the link to my site: https://i.stack.imgur.com/RcNtv.png .login-top .lg-in::before { font-family: "Fontawesome"; ...

Change occurring within a cell of a table that has a width of 1 pixel

In the code snippet below, there is a transition inside a table cell with a width of 1px to allow it to wrap its content. However, the table layout changes only at the end or beginning of the transition: var animator = document.getElementById("animator" ...

Achieving Dynamic Center Alignment of Filtered Node in SVG Using D3

I am currently implementing filter functionality for my d3 graph. The goal is to allow users to search for a specific node by label or ID, then re-render the graph to display the entire structure with the filtered node positioned at the center of the SVG e ...

Exploring the analysis of JavaScript and CSS coverage throughout various pages or websites

The Chrome Dev Tools JavaScript and CSS Coverage Drawer is quite impressive, but there is one thing that could make it even better. It would be great if it could remain active without restarting its analysis every time you visit a new page. I wish I could ...

How do I switch back and forth between displaying content as 'none' and 'block' using JQUERY?

Take a look at this code snippet. <div class="sweet-overlay" tabindex="-1" style="opacity: 1;display: none;"></div> Is there a way to switch the style attribute value from none to block and back? ...

Upon returning to the previous page, the checkbox remains checked and cannot be unchecked

Here is the code I'm using to append checkbox values with a hash in the URL. However, when navigating back, the checkboxes remain checked. Take a look at the code snippet below: <html> <head> <script src="http://ajax.googleapis.com/aja ...

Expand a div without causing any displacement to surrounding elements

If you have 4 colored divs (red, yellow, green, blue), with 2 per row, and need to expand the second (yellow) without creating a gap under the red, check out this solution. The blue will be positioned underneath the expanded yellow. For a live example, vi ...

Modifying the appearance of Bootstrap 4 Nav-tabs using CSS

I have implemented Bootstrap 4 Nav-tabs as shown below: <ul class="nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" ...

Having trouble retrieving JSON data from an AJAX request and showing it in an HTML page

Having some trouble with utilizing the New York Times bestseller list API to showcase the current top 20 in html. I've successfully retrieved the data using ajax (confirmed through developer tools) but hit a roadblock when attempting to display it on ...