Unable to modify CSS property following AJAX request

I'm currently making an ajax call and attempting to add a class to a DOM element, followed by changing a property value of that class.

Although I am able to add the class successfully, I am facing issues when trying to change the attribute.

<script>
function load_to_be_analysed_count() {
    $.ajax({
        url: 'experiments/to_be_analysed/count',
        dataType: 'text',
        type: 'get',
        success: function(data) {
            // data represents the number of experiments to be analysed, retrieved from the server
            if (data >= 0) {
                $('#new_experiments').addClass('badge');
                console.log($('.badge').css('content'));  // DEBUG
                $('.badge').css('content', data);
            }
        },
        error: function () {
            $('#login-language').html('<p>An error occurred</p>'); // TODO: for debugging purposes. Maybe use console.log
        }
    });
    if ($('#new_experiment').hasClass('badge')) {
  
        $('.badge')
    }
}
$(function () {
    load_to_be_analysed_count()
})
</script>

Original HTML:

<i id="new_experiments" class="fa fa-bell fa-2x icon-grey"></i>

Upon loading the page, the Inspector shows none when

console.log($('.badger').css('content'));  // DEBUG
is reached.

In the Inspector, I observe that the above HTML has been modified to

Updated HTML:

<i id="new_experiments" class="fa fa-bell fa-2x icon-grey badge" style=""></i>

CSS:

i#new_experiments {
  width: 50px;
  text-align: center;
  vertical-align: middle;
  position: relative;
}
.badge:after{
    content: "50";
    position: absolute;
    background: red;
    height: 2rem;
    top: -0.2rem;
    right: 0.2rem;
    width: 2rem;
    text-align: center;
    line-height: 2rem;
    font-size: 1rem;
    border-radius: 50%;
    color: white;
}

Answer №1

In reference to this discussion, it is noted that accessing :before and :after in jQuery is not possible as they are not considered part of the DOM. The use of the content attribute is limited to these two pseudo classes.

To work around this limitation, a structural change may be necessary. One approach could involve creating an Element with position: relative/absolute instead of relying on :after/:before, followed by utilizing something like the following:

$('.badger').html(data);

Answer №2

If you want to enhance the visual style of your website, consider adding a new CSS tag with the provided content

    success: function(data) {
        // The server returns the number of experiments to be analyzed as 'data'
        if (data >= 0) {
            $('#new_experiments').addClass('badger');
            console.log($('.badger').css('content'));  // DEBUG
            $('head').append('<style>.badger::after{content:"' + data + '"}</style>');
        }
    },

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

Guide on Redirecting in Express.js

I am seeking assistance with finding solutions. In short, I have created this API () with username: test and token: test. If the current date is past the meeting time, then open the meeting URL in a new tab. This check should occur every second. ...

Sentry alert: Encountered a TypeError with the message "The function (0 , i.baggageHeaderToDynamicSamplingContext) does not

My website, which is built using Next.js and has Sentry attached to it, runs smoothly on localhost, dev, and staging environments. However, I am facing an issue when trying to run it on my main production server. The error message displayed is as follows: ...

Performing CRUD operations on a single page form in Laravel 6

In my database, I store contact details in a table. The form on my website includes a Dropdown menu that lists the names of different people. When I select a name from this Dropdown, the form fields are automatically populated with the respective contact d ...

When trying to find a substring within a string in JavaScript, the "else if" statement may not be triggered

I'm currently working on creating a Hangman game using HTML and JS. Most of the code is functioning properly, but I've hit a roadblock. For some reason, one part of my if else statement isn't working correctly. Here's the line of code: ...

Vue.js: The href attribute in a link is different from the data

Having <a> href tag below, clicking will redirect to www.duckduckgo.com, with the value of page.publicWebsite being displayed as well. {{page.publicWebsite}} shows www.duckduckgo.com. Is everything functioning correctly? https://i.stack.imgur.com/ ...

Unable to upload a file via Safari when using Angular.js

Having trouble uploading a file using Win7 and Safari with the ng-file-upload feature in Angular.js. Below is my code: <div ng-repeat="mul in mulImage"> <input type="file" class="filestyle form-control" data-size="lg" name="upload_{{$index}}" ...

Exploring the concept of nested forms in Django

I have a requirement to implement nested Django forms using the following models: class Publisher(models.Model): name = models.CharField(max_length=256) address1 = models.CharField(max_length=256) address2 = models.CharField(max_length=256) ...

What is the best way to allow a container div to only show horizontal overflow, without relying on "display:inline-block" for its inner divs?

My coding challenge involves dynamically creating nested <div> elements within another <div> when a button is clicked. Upon clicking the button, a new inner <div> with a unique id is generated inside the outer <div>, each possessing ...

Several directories containing references to PHP and CSS files

I'm encountering an issue with my PHP file named header.php. Here is the content of the file: <title><?php echo $title; ?></title> <link href="core/css/styles.css" rel="stylesheet" /> <link href="core/css/bootstrap.css" re ...

Can you recommend a resource that provides a comprehensive breakdown of which CSS elements are compatible with each internet

Can anyone recommend a comprehensive resource, such as a book or website, that provides a complete list of CSS elements and their compatibility with the major web browsers? Specifically, I am interested in information regarding compatibility with IE8 and F ...

Localhost causing variations in CSS behavior

I've been working on a website and wanted to share it with someone, so I set up a webserver. However, I've encountered some peculiar behavior when trying to access the site via LAN rather than through my localhost. Firstly, when viewing the site ...

Ion-row appears out of frame

This is a simple layout: <ion-content> <ion-grid *ngIf="loaded"> <ion-row> <ion-col>Stuff</ion-col> <ion-col>Stuff</ion-col> <ion-col>Stuff</ion-col> </ion-row> < ...

Getting an array in PHP and then displaying it accurately using jQuery

In my index.php, I have an AJAX request to a file called get_code.php. This file queries a database and returns an array encoded with json_encode back to index.php. In the index page, this JSON array is converted to a string using JSON_stringify. Everythi ...

Typescript - Conditional Type and Optional Arguments

My component has various arguments that can be passed to it: interface Props { label: string; children?: React.ReactNode; withoutActions?: boolean; fieldKey?: KeyProperties; corporate: Corporate; } The withoutActions and fieldKey properties are ...

Is the jQuery trim function malfunctioning on Internet Explorer 7?

I'm attempting to utilize the jQuery text() function and apply the trim() function to eliminate any leading or trailing whitespace. This method works perfectly in Firefox, but unfortunately does not produce the desired results in IE7 (it persists in r ...

What could be causing the first bar in Chart.js to appear smaller or not show up at all?

Hey there, I'm currently working on displaying some bar charts using Charts js. However, I've run into an issue with the first column not showing up correctly. Here is my code snippet: var options = { scales: { yAxes: [{ display: tru ...

Guide on using jQuery to assign an element's content to the value of its attribute

While experimenting with jsFiddle, I came up with this exercise for myself. Imagine you have elements with a data attribute like this: <div data-test-id="3214581">Loading...</div> <div data-test-id="6584634">Loading...</div> The ...

Exploring Updates in Two Objects Using a Loop in JavaScript

Two different Objects are structured as follows: Obj1: { 0: {name:"", id: 0}, 1: {"age": "", id:0}, 2: {name:"", id: 1}, 3: {"age": "", id:1}, } After triggering a property, the structure ch ...

An issue has arisen with the TypeScript function classes within the React Class, causing a compile error to be thrown

I am currently in the process of transitioning a React object from being a function to a class. This change is necessary in order to save the state and bind specific functions that I intend to pass to child components. Unfortunately, during compilation, I ...

When working with a JavaScript array of class objects, it may appear as though the array is empty when it

Currently puzzled by the behavior of this array. Despite my efforts to find an answer, I haven't had any luck so far. I initialize var allMenuItems = []; at the top and then in getMenuItems(), I push multiple new class objects. However, when I call co ...