Caco
Caco

Reputation: 1654

Can't change css property after ajax call

I'm doing an ajax call an trying to add a class to a DOM element, and then change a value of a property of that class.

I can add the class, but not changing the attribute.

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

HTML before:

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

When I load the page, Inspector display none when console.log($('.badger').css('content')); // DEBUG is reached.

In Inspector, I can see the above HTML changed to

HTML after:

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

CSS:

i#new_experiments {
  width: 50px;
  text-align: center;
  vertical-align: middle;
  position: relative;
}
.badger: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;
}

Upvotes: 1

Views: 1332

Answers (2)

Musa
Musa

Reputation: 97672

You could try adding a new style tag with the given content

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

Upvotes: 1

Schlumpf
Schlumpf

Reputation: 376

Regarding to this post you can't access :before and :after in jQuery as they are not part of the DOM. The content attribute only works with those two pseudo classes.

You have to change your structure I think. A possibility would be to create an Element that has position: relative/absolute without using :after/:before and then do something like:

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

Upvotes: 2

Related Questions