Home > Software engineering >  How to do long list of parameters in jQuery function
How to do long list of parameters in jQuery function

Time:10-27

I have a long list of parameters I have to pass into a jQuery .removeClass function.

How do I add them all into one parenthesis separated by commas? Currently it looks like this...

     $("#bottom-nfl").click(function(){
        $("#bottom-mlb i, #bottom-mlb small").removeClass("orange");
        $("#bottom-nba i, #bottom-nba small").removeClass("orange");
        $("#bottom-ncaab i, #bottom-ncaab small").removeClass("orange");
        $("#bottom-profile i, #bottom-profile small").removeClass("orange");
    });

But I want it to look like this:

     $("#bottom-nfl").click(function(){
        $("#bottom-mlb i, #bottom-mlb small,
        #bottom-nba i, #bottom-nba small,
        #bottom-ncaab i, #bottom-ncaab small
        #bottom-profile i, #bottom-profile small").removeClass("orange");
    }); 

But that resultes in unterminated string literal error.

I tried with the backslash to escape the newlines but that doesn't work either

CodePudding user response:

You need template literals here if you want to split the string and that allows you to format the list

Also you missed a comma

 $("#bottom-nfl").on("click", function(){
    $(`#bottom-mlb     i, #bottom-mlb     small,
       #bottom-nba     i, #bottom-nba     small,
       #bottom-ncaab   i, #bottom-ncaab   small,
       #bottom-profile i, #bottom-profile small`).removeClass("orange");
}); 

or program it

$("#bottom-nfl").on("click", function(){
  ["mlb","nba","ncaab","ncaab","profile"]
    .forEach(cls => $(`#bottom-${cls} i, #bottom-${cls} small`).removeClass("orange"));
}); 

Actually escaping the newline SHOULD work, but the template literals are prettier

 $("#bottom-nfl").on("click", function(){
    $("#bottom-mlb     i, #bottom-mlb     small,\
       #bottom-nba     i, #bottom-nba     small,\
       #bottom-ncaab   i, #bottom-ncaab   small,\
       #bottom-profile i, #bottom-profile small").removeClass("orange");
}); 
  • Related