Using jQuery to change the background color of a box both before and after elements

This is an example that I created: http://jsfiddle.net/YXqu2/

I am seeking assistance.

I have added a box in my HTML with before and after elements. Using jQuery, I randomly give the box elements some backgrounds. I also want to change the border color of the before and after elements. I have tried writing some code but it doesn't seem to be working. Can someone please help me?

Apologies for any mistakes in my English.

Thank you

Answer №1

It is not possible to use jQuery to directly modify the styles of pseudo classes because they cannot be selected. However, a workaround is to inject a new style element into the head section to achieve the desired styling changes.

HTML

<div class="container">
Container       
</div>

JS

var redAfter = jQuery('<style>.container:after{border:1px solid #F00; }</style>');
var blueAfter = jQuery('<style>.container:after{border:1px solid #00f; }</style>');

jQuery("#change1").click(function(){
   blueAfter.remove();
   jQuery("head").append(redAfter);
});

jQuery("#change2").click(function(){
   redAfter.remove();
   jQuery("head").append(blueAfter);
});

Fiddle Demo

There may be performance issues with this method, especially if there are many pseudo elements that need to be modified. It is advisable to keep track of the injected styles and remove them when no longer needed. Additionally, compatibility across different browsers may vary, although it has been tested to work in Chrome.

If possible, consider using actual objects instead of pseudo elements in your code for better maintainability and performance.

Answer №2

I attempted to enhance the structure by incorporating DIVs for arrows alongside your current append() function, and updating the pseudo classes to regular classes.

JS :

$(".line").append("<div class='arrowLeft' style='border-left:12px solid " + random_color + ";'></div><div class='arrowRight' style='border-right:12px solid " + random_color + ";'></div><div class='lines_type' style='background:" + random_color + ";'></div>");

CSS :

.line .arrowLeft {
    border-bottom: 7px solid transparent;
    border-left: 12px solid orange;
    border-top: 7px solid transparent;
    content:"";
    height: 0;
    margin-right: -4px;
    margin-top:70px;
    float:right;
    width: 0;
}
.line .arrowRight {
    border-bottom: 7px solid transparent;
    border-right: 12px solid orange;
    border-top: 7px solid transparent;
    content:"";
    height: 0;
    margin-left: -4px;
    margin-top:70px;
    float:left;
    width: 0;
}

Fiddle

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

Distinguishing between these two hover text types: JQuery CSS, what sets them apart?

As a total jQuery novice, I've been curious about the difference between these two types of text that appear when you hover over something. Can someone please clarify what each one is? Thank you very much. First hover text: When hovering over the up- ...

Content fully displayed, excess content cropped

Upon examining the layout of this DOM structure, I noticed a flexbox container with two children. One child has a fixed size, while the other one shrinks with an overflow: hidden. My curiosity lies in finding a way for the content that overflows to remain ...

Encountering a problematic JQuery Ajax request to a RESTful API

I am currently in the process of trying to authenticate against demo webservices that were developed by one of my colleagues. While Cross-origin resource sharing is allowed and functions perfectly when I attempt to call from the Advanced Rest Client plugin ...

Utilize custom fonts from your local directory within a Vite Vue3 project

Inside my main.scss file, I am loading local fonts from the assets/styles/fonts folder: @font-face { font-family: 'Opensans-Bold'; font-style: normal; src: local('Opensans-Bold'), url(./fonts/OpenSans-Bold.ttf) format('truety ...

Two dropdown menus opening simultaneously

Recently, I encountered an issue while using a dropdown menu within a div. Even though it was functioning properly, I noticed that when I included two dropdown menus on the same page, clicking on the first one would cause both the first and second dropdown ...

Is the Nopcommerce theme being upgraded from version 2.3 to 3.0?

I am new to nopCommerce and facing a challenge. I need to upgrade a nopCommerce 2.2 site to version 3.0, but only the theme. I already have two sites designed, and I want to apply the 3.0 theme to the 2.2 site. If it were just a simple HTML page, copying ...

Achieving the perfect horizontal alignment of images

Currently working on a new project and here's the page I'm focusing on: The elements are exceeding the set height of their container and overlapping into the content area instead of pushing the existing content down. Any suggestions to fix this ...

Fixed footer positioned at the bottom of the page regardless of the amount of content present

I'm facing an issue where the footer is not sticking to the bottom of the page as intended. When there is less content, it should be displayed without any scroll, and if there is more content, the footer should appear at the end. Here is the code I am ...

Performing multiple Ajax requests on a single page

On my homepage, I have 3 columns set up. The first column displays all the categories from a database, the second column shows the subjects related to a category when clicked, and the third column displays the contents when a subject is clicked. My goal i ...

Ways to resize column widths in tree views on Odoo version 10?

I have been struggling to adjust the column width of the columns in my tree view. I have attempted a few different solutions: Trying to change the width attribute in the field tag: width="100px" or width="15%%" Using the style att ...

Interactive form featuring text fields and dropdown menus

Is it possible to create a form with the ability to add new rows consisting of SELECT and INPUT elements? Although my current code allows for this, I am facing an issue where no variable from the SELECT element is posted when the form is submitted. This i ...

Convert the table into an array

Hello everyone, I have a table here <table> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr> <td>Jill</td> <td>Smith</td> ...

How come my script that is dependent on the viewport does not apply classes?

I created a code to add a class to a div, but it's not working as expected. I need help troubleshooting this issue. The code works fine on codePen, but not on my WordPress website. How can I make sure the browser executes this code properly? Link to ...

Different method for adding child elements to the DOM

When creating a DOM element, I am following this process: var imgEle = document.createElement('img');     imgEle.src = imgURL;             x.appendChild(imgEle); Instead of appending the last line which creates multiple img elements ev ...

Display Bootstrap modal automatically upon page load three times for each individual user

i need the bootstrap modal to appear on page load and i have come across the following code. However, there are a couple of issues: 1- I want the modal to display for every user three times, not just the first time! How can I achieve that, my friends? 2 ...

Struggling to align the login button accurately within the navbar

For proper alignment, the "Login" button needs to be pushed to the right of the navbar alongside other buttons. To see the issue and the code, check out this JSFiddle example: https://jsfiddle.net/sterlingmd17/tk17zjfq/1/ <nav class="navbar navbar ...

Tips on changing the text alignment in ant design's Select with search field component within a Form item to support various languages

Is there a way to dynamically change the text direction in a search field based on the language being typed by the user? For example, switch the direction to rtl when typing in Arabic and to ltr while typing in English. I need to achieve this functionalit ...

Showing Stationary Pictures at Full Size in OpenLayers

I am trying to showcase static images as maps using a StaticImage layer in ol3, with the image size set at 100% in pixels. However, I am facing difficulty in ensuring that the displayed images are always the correct size based on the extent and zoom variab ...

When the page finishes loading, execute a Javascript or JQuery script

I am struggling to display the feedback from the two functions, correct[] and wrong[], as the user responds to the questions. I have attempted to use the jQuery ready function in order to ensure that everything appears before the prompts, but so far it has ...

Embedding the scrollbar within the div container

I'm having trouble placing my vertical scrollbar inside my div and adjusting its position. To streamline the code, I have extracted a portion below: .toprightcontrols { margin: 0 3% 0 0; display: flex; position: absolute; justif ...