Add CSS rule via jQuery for future created elements

JavascriptJqueryCss

Javascript Problem Overview


I have a somewhat unusual issue. I've done something like this many times:

$('#selector').css('color','#00f');

My problem is that I create a <div id="selector">, and I call the command above and it works fine.

Now, on another event, later, I remove that element from the DOM and add it again at a later time with the same id. This element now doesn't have color:#00f.

Is there a way that I can add a rule in CSS, such that it will affect items that are created in the future with that same id/class? I like jQuery, but anything with plain JavaScript would be fine as well.

It has to be dynamic, and I don't know the classes to put in a CSS file. Also, I plan on changing a single attribute a few different times through the course of the application. For example, setting the color to black, to blue, to red, and back to black.



I went with the answer from @lucassp, and this is what I ended up with:

function toggleIcon(elem, classname)
{
    if($(elem).attr('src')=='img/checkbox_checked.gif')
    {
        $(elem).attr('src', 'img/checkbox_unchecked.gif')
        //$('.'+classname).hide();//this was the old line that I removed
        $('html > head').append($('<style>.'+classname+' { display:none; }</style>'));
    }
    else
    {
        $(elem).attr('src', 'img/checkbox_checked.gif')
        //$('.'+classname).show();//this was the old line that I removed
        $('html > head').append($('<style>.'+classname+' { display:block; }</style>'));
    }
}

I also want to say that @Nelson is probably the most "correct", though it would require more work to go into application code that always works fine, and that's not effort I want to spend at the moment.

If I had to rewrite this (or write something similar) in the future, I would look into detach().

Javascript Solutions


Solution 1 - Javascript

This should work:

var style = $('<style>.class { background-color: blue; }</style>');
$('html > head').append(style);

Solution 2 - Javascript

When you plan to remove elements from the DOM to re-insert them later, then use .detach() instead of .remove().

Using .detach() will preserve your CSS when re-inserting later. From the documentation:

> The .detach() method is the same as .remove(), except that .detach() > keeps all jQuery data associated with the removed elements. This > method is useful when removed elements are to be reinserted into the > DOM at a later time.

Solution 3 - Javascript

In case this style section suppose to be changed several times, you can set in the html file a style tag with id:

<style id="myStyleTag">
</style>

then you can refer it with js, edit or remove content like:

var style = $('#myStyleTag');
styl.html('.class { background-color: blue; }');

in this way the style section will not become bigger if you change it several times because you don't just append it to the head but edit it as needed.

Solution 4 - Javascript

Here is some JavaScript code I wrote before to let me add, remove and edit CSS:

function CSS(sheet) {

    if (sheet.constructor.name === 'CSSStyleSheet' )
        this.sheet = sheet;
    else if (sheet.constructor.name === 'HTMLStyleElement')
        this.sheet = sheet.sheet;
    else
        throw new TypeError(sheet + ' is not a StyleSheet');
}

CSS.prototype = {
    constructor: CSS,
    add: function( cssText ) {
        return this.sheet.insertRule(cssText, this.sheet.cssRules.length);
    },
    del: function(index) {
        return this.sheet.deleteRule(index);
    },
    edit: function( index, cssText) {
        var i;
        if( index < 0 )
            index = 0;
        if( index >= this.sheet.cssRules.length )
            return this.add(cssText);
        i = this.sheet.insertRule(cssText, index);
        if (i === index)
            this.sheet.deleteRule(i + 1);
        return i;
    }
};

And then if a new stylesheet is required, construct as

var myCss = new CSS(document.head.appendChild( document.createElement('style')));

Solution 5 - Javascript

The best option would be to add a class:

.selected {
    color : #00f ;
}

$('#elemId').addClass('selected')

Solution 6 - Javascript

You can use livequery plugin.

$('#selector').livequery(function() { $(this).css('color', '#00f'); });

Solution 7 - Javascript

This is an old question with a chosen answer, but adding dynamic CSS to accomplish the goal is not necessary and is likely sending people in the wrong direction.

If you want to dynamically set styles on an element using jQuery, it is best to use .addClass() and .removeClass() with classes that affect the required style.

Given the function in the question:

function toggleIcon(elem, classname)
    {
      if($(elem).attr('src')=='img/checkbox_checked.gif')
    {
        $(elem).attr('src', 'img/checkbox_unchecked.gif');
        $("." + classname).addClass("hidden");
    }
    else
    {
        $(elem).attr('src', 'img/checkbox_checked.gif');
        $("." + classname).removeClass("hidden");
    }
}

And then just add this to your CSS:

.hidden {display: none;}

This would also work to change color, as also mentioned in the question:

.checkbox-red {color: red;}
.checkbox-blue {color: blue;}

Solution 8 - Javascript

There is nothing wrong with the accepted answer. But if you wanted to do this in just one line, you could do something like this:

$('<style>').append('.'+classname+'{display:none}').appendTo('head')

Solution 9 - Javascript

Create a CSS rule in your CSS file

.yourclass{
    color: #00f;
}

Add yourclass whenever you're creating the element:

$("#selector").addClass("yourclass");

Solution 10 - Javascript

Just use a class, for example:

CSS:

.setcolor { color: #fff; }

JavaScript:

$('#selector').addClass('setcolor');

Then remove it when needed:

$('#selector').removeClass('setcolor');

Solution 11 - Javascript

If you already have a style element in your document, you can just add another rule to it with vanilla js:

document.styleSheets[0].addRule('#selector', 'color: #00f');

Solution 12 - Javascript

Try this

var style = $('<style>.class { background-color: blue !important; }</style>');
$('html > head').append(style);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLandonView Question on Stackoverflow
Solution 1 - JavascriptlucasspView Answer on Stackoverflow
Solution 2 - JavascriptNelsonView Answer on Stackoverflow
Solution 3 - JavascriptamichaiView Answer on Stackoverflow
Solution 4 - JavascriptPaul S.View Answer on Stackoverflow
Solution 5 - JavascriptSushanth --View Answer on Stackoverflow
Solution 6 - JavascriptAlmir SarajčićView Answer on Stackoverflow
Solution 7 - JavascriptKhanView Answer on Stackoverflow
Solution 8 - JavascriptPHP GuruView Answer on Stackoverflow
Solution 9 - JavascriptAnoopView Answer on Stackoverflow
Solution 10 - JavascriptgregwhitworthView Answer on Stackoverflow
Solution 11 - JavascriptProtector oneView Answer on Stackoverflow
Solution 12 - JavascriptcodemirrorView Answer on Stackoverflow