Is it possible to use HTML text as a CSS selector with JavaScript?

I've been searching for a solution to this issue but haven't found anything that works for me.

Check out this code on jsfiddle.

Person1 and Person2 both have

class="from"

and the CSS selector is .from so it applies to both. However, I want it to only apply to Person1 using JavaScript/jQuery.

I've attempted various methods like

$( "span.from:contains('Person1')" )

but nothing seems to work. Can someone suggest a solution?

Your help would be greatly appreciated :)

Answer №1

If you're in a similar situation, consider utilizing the filter() function

$("span.from").filter(function(){ return this.innerHTML == "Person1"; })

To eliminate the animation on the object, simply remove the from class with removeClass()

$("span.from").filter(function(){ 
     return this.innerHTML == "Person1"; 
}).removeClass('from');

Answer №2

$( "span.from:contains('Person1')")
functions correctly. However, in css, the impact is still on all elements with the .from class. Once you have obtained the element using Javascript, take some action such as adding a new class and adjusting the css so that the animation only applies to the new class.

$( "span.from:contains('Person1')").addClass('newClass')

CSS:

.newClass{
    -webkit-animation: color-change 1s infinite;
    ...
}

Answer №3

Your script is effective

$("span.from:contains('Person1')").text()

Take a look at this demonstration

Answer №4

If you are utilizing pure CSS, it is possible to specifically target the first element using the nth-child selector:

.from:nth-of-type(1) { /* custom styles */ }

However, if you prefer to select the first item using JavaScript, you can simply utilize eq() to access the first item based on its index. This method allows for chaining, enabling you to apply additional CSS properties to this element. For instance, the following code snippet adds an extra class to the first .from element and changes its background color:

$(".from").eq(0).addClass("first-item").css("backgroundColor", "orange");

Answer №5

One possible solution is to utilize the .not() method.

$(".from:not(span:contains('Person2')):eq(0)")

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

Tips for arranging flex children on top of one another

I am looking to position and center both boxes so that they overlap in the middle of the screen, without specifying a fixed width and height. Additionally, I want to incorporate CSS transitions to make box 1 disappear and reveal box 2 upon clicking a butt ...

When passing a numeric value like 1 or 2 to the function in ajax, it functions correctly. However, when attempting to parse a variable, it does

I am facing an issue with my AJAX function. It works perfectly fine when I pass a number as a parameter, but not when I pass a variable. function display_message(userID) { $.ajax({ url: "displaychat.php", method: "post", data: { toui ...

Leverage the power of Angular's library dependency injection with the @inject

I am currently working on a project that involves a library. Within one of the classes in this library, I am attempting to provide a service using @optional, @host, and @inject decorators with an injection token. In the parent component, I have the optio ...

How can a non-commonJS library be effectively integrated into the Webpack environment?

Looking to incorporate an external and non-commonJS library to define an AngularJS module. What is the best approach since directly importing it won't work, like this: import MyLibrary from 'MyLibraryPath' angular.module('MyApp' ...

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 ...

The Ajax response is not providing the expected HTML object in jQuery

When converting HTML data from a partial view to $(data), it's not returning the jQuery object I expected: console.log($(data)) -> [#document] Instead, it returns this: console.log($(data)) -> [#text, <meta charset=​"utf-8">​, #text ...

Having trouble with the dropdown menu in Bootstrap?

I'm having trouble creating a responsive dropdown menu. When I click on the dropdown items, nothing happens. Here's the code: <div class="navbar-header"> <button type="button" class="navbar-toggel" data-toggel="collapse" data-target="#m ...

Module Ionic not found

When I attempt to run the command "ionic info", an error is displayed: [ERROR] Error loading @ionic/react package.json: Error: Cannot find module '@ionic/react/package' Below is the output of my ionic info: C:\Users\MyPC>ionic i ...

Setting the height of children within an absolutely-positioned parent element

I am facing an issue with adjusting the size of children elements based on their parent. The scenario is as follows: HTML <div class="video"> <div class="spot"> <img src="..." alt=""> <button>x</button> </div ...

Tips for creating a two-tier selection filter system

I'm having an issue with this code. My objective is to create two filters for this table. The select element with id="myInput" should determine which rows appear in the table and apply the first filter. Here is the JavaScript code: function myFunctio ...

Tips on targeting a node that is dynamically generated within a function and styling it externally

Is there a way to style or change divs created within a function, but without making the change within that same function? Since variables are in the local scope of functions, it can be challenging to access these created divs for future styling or changes ...

Incorporating the fadeout technique in conjunction with the append() function

Here is some code that I am working with: $('body').on('click' , function(){ $('body').append('<div class="ajax-success"><p>Its Done !!!</p></div>').fadeOut(2000); }); The goal was to a ...

Exploring SVGO CLI: A guide to inspecting SVGs across various directories

Currently, I am utilizing the SVGO CLI script to transform some icons within my project. Specifically, these icons are located in two separate folders - assets/icons/dark-mode and assets/icons/light-mode. My goal is to navigate through both of these folder ...

Unable to bring in the specified export 'Directive' from a non-EcmaScript module - only the default export is accessible

I am currently working on an ionic angular project and utilizing the ng-lazyload-image plugin. However, I am encountering errors during compilation that look like this: Error: ./node_modules/ng-lazyload-image/fesm2015/ng-lazyload-image.mjs 401:10-19 Can ...

Exploring the distinctions between ajax, await, async, and

English is not my strong suit, so please bear with me if my writing seems odd. We have discovered two methods for transitioning from asynchronous ajax calls to synchronous ones. Using async: false Utilizing await Both achieve the same outcome, but I am ...

Access the JSON data stored in the File Directory by reading and utilizing it for your project

Can someone help me figure out how to retrieve data from the xmltojson.json file and assign it to a variable using JavaScript? const jsonfile = require('jsonfile') const file = 'xmltojson.json' jsonfile.readFile(file, function (err, obj ...

Collect input from the user for multiple lists and send them to PHP for additional processing

I'm struggling to find the error in this code... I keep getting "undefined index user_list" as the error message. Essentially, I am trying to allow users to input values into a list and then store that entire list in a database. <?php if(isset($_ ...

The issue of the footer kicking out of place in the HTML layout was successfully resolved after

I am in the process of creating a simple footer that will always stay at the bottom of the page. The content on the page will not exceed the screen size, eliminating the need for scrolling. (There are a total of 5 HTML pages, and I want the footer and head ...

Utilizing setCustomValidity in Bootstrap 4 to dynamically display error messages in .is-invalid classes

The documentation for Bootstrap mentions that custom validity messages can be provided using setCustomValidity in JavaScript. According to the documentation, custom validity messages can be set using the setCustomValidity method in JavaScript. As inter ...

What purpose does the .set() function serve in Node.js with Express?

As I delve into learning Node syntax, there's this particular code snippet that has caught my curiosity. Can you shed some light on its purpose? server.set('views', __dirname); ...