Change the CSS of a selector using jQuery before it is triggered

I am attempting to manipulate the CSS :before and :after selectors using jQuery. Despite trying various methods, it appears that the DOM is unable to access these CSS selectors. My goal is to dynamically change the background-color of an element.

For instance:

.className:before {background: red;}

Eventually, I aim to update this color dynamically:

$('.clasName:before').css('background-color', bgColor);   //this approach does not seem to work

I have also attempted:

$('.clasName').addClass('change').attr('data-background', bgColor); 
//this method only affects the content property

CSS

.className.change:before {
 background: attr(data-background);
}

Unfortunately, neither of these methods are successful. Is there a workaround for this specific issue?

Answer №1

(function($) {
  jQuery.fn.extend({
    retrievePseudo: function(pseudo, property) {
      var props = window.getComputedStyle(
        $(this.selector).get(0), pseudo
      ).getPropertyValue(property);
      return String(props);
    },
    modifyPseudo: function(_pseudo, _property, newProperty) {
      var element = $(this);
      var styleElement = $("style");
      var currentProperty = element.retrievePseudo(_pseudo, _property);
      console.log(currentProperty)
      var regex = currentProperty !== "" ? new RegExp(currentProperty) : false;
      var selector = $.map(element, function(value, key) {
        return [value.tagName, value.id 
                ? "#" + value.id : null, value.className ? "." + value.className 
                : null]
      });
      var modifiedProperty = "\n" + selector.join("")
        .concat(_pseudo)
        .concat("{")
        .concat(_property + ":")
        .concat(newProperty + "};");
      ((!!regex ? regex.test($(styleElement).text()) : regex) ? $(styleElement).text(function(index, prop) {
        return prop.replace(regex, newProperty)
      }) : $(styleElement).append(modifiedProperty));
      return this
    }
  })
})(jQuery);

$(".className").modifyPseudo(":before", "background", "blue");
.className:before {
  background: red;
  content: "123";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>

<div class="className">abc</div>

Answer №2

Modifying the appearance of pseudo elements using JavaScript is not possible, however a workaround is to insert a <span> within your .className and style that instead.

$('.className span').css('background-color', customColor);

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

Exploring the intricacies of multidimensional array scopes in AngularJS

I have a JSON value that includes a list of countries and states. I want to split this value into two different scopes: $scope.countries and $scope.states. When the country is changed, the state should change based on the selected country. Sample JSON da ...

Prevent elements from overlapping within a flexbox container

I've encountered an issue with resizing the window causing the logos to overlap the portrait image. Is there a way to fix the logos relative to the portrait? Below is the code: /* Defaults for Main Part of Pages */ body, div, h1, p { margin: 0; ...

In JavaScript, what is the best way to target the initial option element in HTML?

As a newcomer to javascript, I'm wondering how to target the first option in the HTML <option value="">Choose an image...</option> without altering the HTML itself? My thought is: memeForm.getElementById('meme-image').getElement ...

Pass the variable to another page (Deliver a message)

If the registration and login pages are completed, is it possible to pass a variable from the registration page to the login page? I aim to notify the user that the account has been successfully created. The notification should appear similar to this: Che ...

Tips for refreshing the tawk.to widget when the language changes with the help of i18next

Utilizing i18n-jquery for language switching and integrating the tawk.to chat widget, I've successfully loaded different languages on page reload. However, due to i18n not refreshing the page (which I don't want to do), I need to figure out how t ...

Flask fails to recognize JSON data when transmitted from Nodejs

I am encountering an issue when trying to send JSON data from Node to Flask. I am having trouble reading the data in Flask as expected. Despite attempting to print request.data in Flask, no output is being displayed. Additionally, when I tried printing req ...

Troubleshooting Jquery Ajax Failure in Laravel 4

Whenever I utilize jQuery Ajax to insert data into the database, a peculiar issue arises. Upon clicking the submit button, my page mysteriously returns blank. To shed light on this dilemma, I decided to employ Firebug for debugging purposes, only to stumbl ...

Missing Home and Search icons on Jquery mobileNavigationBar

I am having an issue where the Home and search icons are not displaying properly in the output. Instead, they are showing up as hyperlinks. Can someone please help me with this? Here is the code I am using: <meta name="viewport" content="width=device ...

Switching Images with Rounded Border on Hover Effect

After carefully crafting a rounded box/button and slicing its first corner, the middle bar (which repeats horizontally to adjust the width of the button text/content), and the last corner, I utilized the following markup: <div id="left-corner"></ ...

JavaScript - Struggles with developing a personalized AJAX function

I have been working on creating a function to manage my AJAX post requests. While I have successfully sent the data, I am encountering difficulties with receiving the response. The function in question is named ajaxPost(paramArray, target). It takes param ...

Discovering mongoose records by comparing against a collection of substrings: A step-by-step guide

If I have an array of different substring search parameters, such as: const subStrings = ["foo", "bar", "baz", "whatever"]; I need to retrieve all the documents in which a string field contains at least one of the listed substrings. For example, with a ...

Adjusting the height of each suggested item in Jquery autocomplete

I am currently facing an issue with the autocomplete input on my web app. The suggested list items have a height that is too small, making it difficult to select one item on a tablet using fingers. .ui-autocomplete.ui-widget { font-family: Verdana, Arial, ...

Implementing a password toggle feature on a form that extends Django's default Authentication Form

Incorporating a password toggle feature has become quite the challenge as I extend Django's AuthenticationForm to create my UserLoginForm. Attempting to implement this feature has proven difficult, especially since I have been unable to make use of th ...

Changing the size of a dynamic watermark png in php

I'm trying to automate the resizing of a watermark to cover 1/4 of an image. The code for the watermark is functioning, but I'm facing issues with resizing it correctly. <?php $image = $_GET['src']; $path_parts = pathinfo($image); ...

Issue encountered: Unable to add MongoDB object to database

Recently, I have encountered an issue with a script that looks like this: use first_db; advertisers = db.agencies.find( 'my query which returns things correctly ); close first_db; use second_db; db.advertisers.insert(advertisers); This error mess ...

Is there a way to locate a specific word within a sentence using JavaScript

I have these lists of answers: For example: const answerList = [{index: 2, answer: nice}, {index: 5, answer: sunday} ...] similar to that Also, I have a sentence: For instance: "hi i'm theo nice to meet you. how are you" My goal is to identify ...

Is Dealing with Multiple AJAX Requests a Pain?

Currently, I am utilizing AJAX to retrieve a list of active streams from TwitchTV along with their viewers, updating every second. Sometimes the stream list can become quite long, so my plan is to divide the AJAX requests into 2 or 3 parts: 1) Obtain Numb ...

What exactly is the purpose of the double ampersand selector, '&&', when it comes to overriding the root class with makeStyles within Material-UI React?

I recently started using Material-UI and encountered an issue where I couldn't override the root class for Avatar, specifically MuiAvatar-root. Material-Ui Version: 4.11.3 Despite following examples provided by material-ui's documentation here, ...

Selenium's Unpredictable Data Points

I'm new to using Selenium and I need help with inserting random values into a Send.Key function within a findElement. I am currently working with Selenium web driver using Java. This is the code I have so far: driver.findElement(By.id("id1" ...

Progress bar enabled JavaScript file uploader

Has anyone discovered the method for achieving multi-file upload using solely Javascript while maintaining a smooth progress bar display for each file? It seems that services like Gmail, Hotmail, and Amazon S3 have already accomplished this. ...