Using jQuery, locate identical text and assign a class to the corresponding container

How can I check if any of the h2 elements match the text in h1, ignoring case sensitivity? If a match is found, I want to add a class to the container Product-div.

<div id="PageHeader">
  <h1>Same text</h1>
</div>

<div class="Product">
  <h2 class="ProductName">Product name 1</h2>
</div>

<div class="Product">
  <h2 class="ProductName">Same text</h2>
</div>

<div class="Product">
  <h2 class="ProductName">Product name 2</h2>
</div>

Answer №1

To implement this solution, first grab the text from the h1 element and convert it to lowercase since text comparison is not case sensitive as per your requirement. Next, loop through all h2 elements and compare their text with the lowercase h1 text. If a match is found, add a class to the parent div.

$(function(){
  var h1Text = $('#PageHeader h1').text().toLowerCase();
    $('.Product .ProductName').each(function(){
       if($(this).text().toLowerCase()==h1Text)
           $(this).closest('.Product').addClass('containerProd');
    });
});

Check out the DEMO here!

Answer №2

Give this a try:

let headerText = $("#PageHeader h1").text();

$('.ProductName:contains("'+ headerText +'")').parent().addClass('Product-div');

The code above should be clear in its functionality.

View DEMO here

To make the query case-sensitive, utilize the following code snippet that changes the contains() function to be case-sensitive:

// Case-sensitive 'contains'
Query.expr[':'].contains = function(a, i, m) { 
  return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0; 
};

let headerText = $("#PageHeader h1").text();

$('.ProductName:Contains("' + headerText + '")').parent().addClass('Product-div');

Check out DEMO2 here

Answer №3

you can attempt the following :

let pageTitle = $('#PageHeader h1').text();
$('.Product ProductName').each(function() {
  if ($(this).text() == pageTitle) {
     $(this).parent('.product').addClass("your custom class");
  }
});

Answer №4

Give this a shot,

let mainHeaderText = $("h1").text();
$.each($("h2"), function(index, value){
  if($(value).text().toLowerCase() === mainHeaderText.toLowerCase())
  {
      $($(this).parent()[0]).addClass("Product-div");
  }
});

Answer №5

Give this a shot:

let headerText = $("#PageHeader h1").text();
$('.Product h2').filter(function(){
    return this.innerHTML.toLowerCase() === headerText.toLowerCase();
}).parent().addClass('Product-container');

View Demo

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

Changing from using GET to employing POST

My current Ajax request function is as follows: // JavaScript function myFunc(pid) { $.ajax({ type : "GET", url : "testback.php", contentType : "application/json; charset=utf-8", dataType : "json", data : { ...

Collection of categories within the drop-down menu

I'm currently utilizing Twitter Bootstrap and would like to create a collection of concealed fields within a dropdown menu: <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#"> Export <b class="ca ...

Tips for centering a flexbox on a webpage:

<template> <div> <div class="flex justify-center w-full"> <div class="h-px-500 md:w-1/6 bg-orange-200 text-center">1</div> <div class="h-px-500 md:w-1/6 bg-orange-300 text-center">2</div> <div clas ...

Customize your application with Kendo UI localization features

Is there a more efficient way to localize a front-end application that utilizes a framework like Kendo UI? For example, you can start by dynamically changing text using JavaScript: $(document).ready(function(){ $("#myText").html(<grab text based on ...

Retrieving data from a dynamic table by utilizing variables

After some testing, I came across a way to select rows from a dynamic table within the range of 2 and 5: var limitTable = $(table).find('tr:gt(2):lt(5)'); However, attempting to use variables in place of hardcoded values doesn't seem to wo ...

What is the best way to customize the woocommerce.css file in the parent theme?

Currently, I have incorporated an ecommerce-friendly wordpress theme for my website in conjunction with woocommerce. To customize the design, I created a child theme and transferred the woocommerce.css file from the plugin into the css of the child theme, ...

Modify content or display picture within accordion panel based on its identifier

In my view, I have a model representing a list of items. Each item has a unique ID, which is included in the H2 header tag. The details of each item are displayed in a div below the header. Initially, there is an image within the header that is set to disp ...

Making Asynchronous Requests in Rails

Is there anyone who can provide assistance with this issue? I've been attempting to make an AJAX request using Rails, but I keep encountering this error message: ActionView::Template::Error (Missing partial client_sub_folders/_client_sub_folder with ...

Is it possible to extract elements from a single list and insert them onto various pages?

Currently, I am retrieving items from a list using an ajax call. After constructing the HTML content, I insert these items onto a page. Now, I want to extract the same items and display them on another page with a different style. Is there a method to conn ...

Enhance Fullcalendar by incorporating an HTML tag alongside the "titleformat" option

I am utilizing the jQuery Fullcalendar agenda feature. My main objective is to link an action with each date that appears in the calendar and enable the opening of a separate window for each date. Therefore, I am looking to include a button or a link next ...

Connect or disconnect an element to a JavaScript event handler using an anonymous function

I'm stuck on a basic issue... I have a custom metabox in my WordPress blog, and here's my event handler: jQuery('tr input.test').on('click', function( event ){ event.preventDefault(); var index = jQuery(this).close ...

Issues with Line Chart in D3: Scaling and Zoom not functioning as expected due to ClipPath limitations

I am utilizing D3 version 4 to process data and create a graph based on dates. Although I have successfully adjusted everything to be compatible with zoom functionality, I am struggling to prevent the line from extending beyond the chart axes. I would pre ...

Tips for utilizing Bootstrap validator to check the size and type of files

Currently, I am utilizing the Bootstrap validator to validate my form. However, I have encountered a challenge with an input field for files where I would like to implement custom validation for file types and sizes (such as pdf, docx, doc...). <div c ...

What is the best way to showcase a chart using jquery?

Is there a way to incorporate trendlines or target lines in highcharts similar to fusion chart? I have been able to draw them successfully in fusion charts. Check out this fiddle link: http://jsfiddle.net/Tu57h/139/ I attempted to recreate the same in hi ...

Ditch the UpdatePanel for JQuery

Currently, I am utilizing UpdatePanel to trigger a button click event asynchronously on a webpage. This event calls a method in a separate class that generates an XML file as the output. I am curious if there is a JQuery alternative to achieve the same f ...

Overlapping borders in Bootstrap 4 design

Working on my project with Bootstrap 4 and encountered a coding issue. Here is the code snippet: .form-info-tab { border: 1px solid #ccc; border-collapse: separate; border-spacing: 0px; padding:5px; text-align:center; } <link ...

html - automatically populating input fields when the page loads

Currently, I have an HTML form embedded in the view and I am looking for a way to automatically populate specific input fields with json variables obtained from the server. Instead of manually writing JavaScript code for each field, my goal is to access th ...

The hidden absolute positioned div disappears once the sticky navbar becomes fixed on the page

Whenever my navbar reaches the top of the screen, the links in the dropdown menu disappear. I followed tutorials and examples from w3schools to build my webpage. Specifically: howto: js_navbar_sticky howto: css_dropdown_navbar This code snippet exempli ...

What is the best way to combine height and min-height in order to ensure that a div always extends to the bottom and keeps

I've tried multiple suggestions without success so far. In my website, I have a main section with white background centered on the page. It stretches nicely to the bottom using flex. See image: https://i.sstatic.net/RmJ2o.png However, there's a ...

Making a div equal in height to an image

What I currently have is like this... https://i.stack.imgur.com/7FeSi.png However, this is what I am aiming for. https://i.stack.imgur.com/fn9m0.png The image dimensions are set up as follows... #content img{ padding: 3%; width: 60%; height: 50%; floa ...