1

So I want to replace 3 css files on a page, with the possibility of a 4th on certain pages... After reading around, I have this:

$("link").each(function(index) {
switch (index) {
    case 1: $this.attr("href","css1.css");
            break;
    case 2: $this.attr("href","css2.css");
            break;
    case 3: $this.attr("href","css3.css");
            break;
    case 4: $this.attr("href","css4.css");
            break;  
}
});

Unfortunately, this doesn't work. I feel I am using "this" incorrectly but I really don't know.

3 Answers 3

3

you're missing the $this reference to the $(this) jQuery Object Element

$("link").each(function(index) {

    var $this = $(this); // dyadaaa!

    switch (index) {
        case 0: $this.attr("href","css1.css");
                break;
        case 1: $this.attr("href","css2.css");
                break;
        case 2: $this.attr("href","css3.css");
                break;
        case 3: $this.attr("href","css4.css");
                break;  
    }

});

The .each() method takes the argument index as a zero based value from the Elements Array collection, so you too, start with 0


Just to share a secret ;) you can do it like:

var links = ['css1.css', 'css2.css', 'css3.css', 'css4.css'];
$('link').each(function( i ){
   $(this).attr("href", links[i]);
});

Or either (if your stylesheets are really named like that) just like:

$('link').each(function( i ){
   $(this).attr("href", "css"+ (i+1) +".css");
});

...where logically (i+1) instead of 0,1,2,3 will return 1,2,3,4

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you sir! Worked perfectly. Don't worry I will guard your secret with my life.
1

Try using $(this) instead of $this

Comments

1

No. you are looking for a jquery wrapper over this then you need to do $(this). But here you can directly assign to the dom element like this.href="css1.css". Also Index is Zero based. so probably you need to handle case 0.

$("link").each(function(index) {
var $this = $(this);
switch (index) {
     case 1: $this.attr("href","css1.css");
        break;
case 2: $this.attr("href","css2.css");
        break;
case 3: $this.attr("href","css3.css");
        break;
 case 4: $this.attr("href","css4.css");
        break;  
}
});

You can write it as , as this here refers to DOM element itself and href can be accessed as a property.

$("link").each(function(index) {

switch (index) {
case 0: ??// Something here?
case 1: this.href ="css1.css";
        break;
case 2: this.href="css2.css";
        break;
case 3: this.href="css3.css";
        break;
 case 4: this.href="css4.css";
        break;  
}
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.