How can jQuery be used to target a specific class based on its inner value?

For instance, within a div of the same class, there are 6 "p" tags - some containing 'member' text and others not. I aim to use jQuery to select all "p" tags with 'member' as their inner text and apply an additional class to them.

Here is the code on which I intend to take action:

<div>
<p class="customClass">Member</p>
<p class="customClass">Non-Member</p>
<p class="customClass">Member</p>
<p class="customClass">Non-Member</p>
<p class="customClass">Member</p>
</div>

This is the expected outcome:

<div>
<p class="customClass member">Member</p>
<p class="customClass">Non-Member</p>
<p class="customClass member">Member</p>
<p class="customClass">Non-Member</p>
<p class="customClass member">Member</p>
</div>

Answer №1

Here's a solution to filter out all .customClass elements that only contain the word "Member" and add the class .member:

$(".customClass").filter(function() {
  return $(this).text().trim() === "Member"
}).addClass("member");
.member {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <p class="customClass">Member</p>
  <p class="customClass">Non-Member</p>
  <p class="customClass">Member</p>
  <p class="customClass">Non-Member</p>
  <p class="customClass">Member</p>
</div>

Answer №2

To target elements with a specific class using jQuery, you can use the following selector:


$(".member").doSomething();

This is a straightforward approach for selecting elements by their class attribute. For further information and advanced techniques, I recommend referring to the official jQuery documentation.

Explore jQuery selectors here

Answer №3

Utilize the code snippet below:

    $("p:contains(Member)")

This jQuery function will retrieve all 'p' tags that include the word 'Member'. You can then assign an extra class using the following code:

    $("p:contains(Member)").addClass("member");

If you specifically want to target only "Members" and exclude "Non-Members", you can try out this code:

    $("p:not(:contains(Non-Member))").addClass("member")

To make the selection more precise, you can experiment with extending the selector text. For instance:

    $(".customClass p:not(:contains(Non-Member))").addClass("member")

This code segment will select all elements with the class "customClass" that do not contain the phrase "Non-Member". It now specifically selects all "p" tags with the class "customClass" that do not have the term "Non-Member" and adds the class "member" to them.

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

Escape from the chains of node.js then() statements

While working with a large amount of externally sourced data, I encounter situations where I need to interrupt the chain of commands and redirect the page. This is an example of my setup: Api file gamesApi.getAllResultsWithTeamInformation(passData) ...

Page freezing due to JQuery scroll event

I successfully implemented a trigger that checks if an element is within the visible viewport and added it to the scroll event. While this works smoothly on some pages, I noticed that on larger pages it causes the page to freeze. In Firefox, I experienced ...

View is unable to trigger the success attribute

Currently, I am delving deep into Backbone JS and facing an issue where the 'success' function in 'EditUser' is not being triggered. I would greatly appreciate it if someone could guide me on what changes I need to make in the code? B ...

Issue with state not being updated upon clicking "Save" button

After setting multiple items in the TransferList component provided by Material-UI, I am encountering an issue when trying to update a state upon clicking "Save". The problem is that the state does not update immediately after clicking "Save"; it requires ...

What could be causing the "Undefned Jquery-ajax" error to pop up

I am struggling with the following code. My goal is to populate values into a dropdown <select> box, but I keep receiving an error of undefined. I have tried switching between Object.keys and Object.values, however, I am still facing the same issue. ...

Ways to terminate and fulfill a promise

Each time I execute this snippet of code, a promise is returned instead of the data being inserted into my database. Unfortunately, I am unable to utilize the await keyword due to it not being in a top-level function. Specifically, I receive the message: & ...

Custom Log4j rollover script to automatically delete logs once the filesystem usage exceeds a specific threshold

Utilizing log4j for logging in my application has been beneficial. I am now exploring the option to automatically delete compressed files when the filesystem reaches 80 percent usage. While log4j lacks a built-in appender for this task, it does offer the S ...

Refreshing a div using ajax technology

I am attempting to use Ajax to update an h3 element with the id data. The Ajax call is making a get request to fetch data from an API, but for some reason, the HTML content is not getting updated. This is how the JSON data looks: {ticker: "TEST", Price: 7 ...

Update the link to a KML file used by Google Maps when a button is clicked

On the initial page load, I want to showcase an 8 Day Average KML file on Google Maps. However, users should have the option to click on the "1 Day" and "3 Day" buttons to switch the reference in Google Maps from the "8 Day" file. The aim is to design a s ...

Need to split your screen into two horizontal DIVs, each with their own scrollbars? Check out this example link for a demonstration!

Hey there! I have a question about creating something similar to this cool website: I'm working with Wordpress and using a child theme for my website. I want to include a fixed header as well. Currently, I've managed to give each div its own sc ...

Develop a library of components using TypeScript and Less files

I'm currently in the process of creating a React UI library that will consist of various components such as Buttons, Inputs, textareas, etc. This library, which I've temporarily named mylib, will be reused across multiple projects including one c ...

Guide on transferring PHP database information to JQuery and then adding it to a Table

Looking to utilize user input to filter and display database data in an HTML table? That's exactly what I'm trying to achieve. My goal is to use the user's input as a filter for querying the database, then present the results neatly in a tab ...

What is the best way to convert my JSON data to HTML using JavaScript?

My dilemma seems to be rooted in the use of backticks. Strangely, an error keeps popping up whenever I try to employ them in my IDE (Brackets). I attempted solutions by testing directly in my Browser and through NotePad++, but unfortunately, nothing seeme ...

Issues with styled-components media queries not functioning as expected

While working on my React project with styled components, I have encountered an issue where media queries are not being applied. Interestingly, the snippet below works perfectly when using regular CSS: import styled from 'styled-components'; exp ...

In the iOS app when the Ionic HTML5 select keypad is opened, a bug causes the view to scroll upwards and create empty space after tapping the tab

I am currently working with Ionic v1 and AngularJS, utilizing ion tabs: <ion-tabs class="tabs-icon-top tabs-color-active-positive"> <!-- Home Tab --> <ion-tab icon-off="ion-home" icon-on="ion-home" href="#/tab/home"> <ion-nav ...

Utilizing long-polling AJAX to connect with a REST API and Memcached in a PHP-based system

Instead of throwing a bunch of buzzwords into my question title, let's get straight to the point. In my PHP application, I am regularly making REST requests through cURL to various webservices. Unfortunately, these requests are experiencing severe la ...

Are there any straightforward methods to fully freeze an object along with all its descendants in JavaScript (Deep Freeze)?

Often when passing an object as a parameter, functions may access the object by reference and make changes to the original object. This can sometimes lead to unwanted outcomes. Is there a way to ensure that an object remains unchanged? I am aware of the Ob ...

Ways to troubleshoot the "TypeError: Cannot read property 'value' of null" issue in a ReactJS function

I keep encountering a TypeError: Cannot read property 'value' of null for this function and I'm struggling to pinpoint the source of the issue. Can someone help me figure out how to resolve this problem? By the way, this code is written in R ...

Issue with HTML 5 audio player not functioning correctly in Chrome browsers when trying to forward or rewind playback

I am encountering an issue with running the HTML5 audio player in Chrome. It works perfectly fine in IE 9+ and Firefox. I have implemented JavaScript functions for forwarding and rewinding the audio player on F7 and F8 key press. These functions work seaml ...

Send the user to an Angular route once they have successfully authenticated with Google

I'm facing an issue with redirecting users to an Angular route. Here's the scenario: When I'm on the login page and click on Google login, I get redirected to Google for authentication. After successfully logging in, I want to be redirecte ...