alexisdwd
alexisdwd

Reputation: 33

Jquery length not working on IE8

Why I´m doing it wrong? It is not loading the amin.css and not even removing the adminNotes.css

if(($(".AdminNoteContainer").length <= 0)){
         $("head").append($('<link rel="stylesheet" href="css/main.css" />'));
         $('head *[href*="css/adminNotes.css"]').remove();
    };

Upvotes: 0

Views: 1414

Answers (1)

gen_Eric
gen_Eric

Reputation: 227290

Your problem is not with the .length (though I don't know why you have <= 0, you can just simply do === 0 or even better if(!$(".AdminNoteContainer").length)), it's with how you're appending the CSS.

IE 8 (and even 9 I think) doesn't let you append <link> tags after the page is rendered. You need to use an IE specific method to add CSS. document.createStyleSheet.

I like to make a getStyleSheet method that will check for the right method of appending CSS. This will use document.createStyleSheet if it's there, if not it'll append a <link> tag.

$.getStyleSheet = function(url){
    if(document.createStyleSheet){
        document.createStyleSheet(url);
    }
    else{
        $('<link />', {
            type: 'text/css',
            rel: 'stylesheet',
            href: url
        }).appendTo('head');
    }
};

Then you can simply do:

if(!$(".AdminNoteContainer").length){
    $.getStyleSheet('css/main.css');
    $('head *[href*="css/adminNotes.css"]').remove();
}

Upvotes: 3

Related Questions