Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add CSS rule via jQuery for future created elements

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().

like image 859
Landon Avatar asked Oct 25 '12 19:10

Landon


People also ask

Can we add CSS in jQuery?

jQuery has several methods for CSS manipulation. We will look at the following methods: addClass() - Adds one or more classes to the selected elements. removeClass() - Removes one or more classes from the selected elements.

Which method is used to apply CSS to any element using jQuery?

jQuery css() Method The css() method sets or returns one or more style properties for the selected elements. When used to return properties: This method returns the specified CSS property value of the FIRST matched element.


4 Answers

This should work:

var style = $('<style>.class { background-color: blue; }</style>'); $('html > head').append(style); 
like image 109
lucassp Avatar answered Sep 20 '22 02:09

lucassp


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.

like image 45
Nelson Avatar answered Sep 21 '22 02:09

Nelson


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')));
like image 27
Paul S. Avatar answered Sep 18 '22 02:09

Paul S.


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.

like image 30
amichai Avatar answered Sep 19 '22 02:09

amichai