Search code examples
javascriptjqueryvariablesdeclare

Can I store mutiple jQuery variables inside a variable?


  const allTeams = johnRoster, paulRoster;

  allLinks.on("click", function () {
    $(allTeams).slideDown(400);
  });

I declared "johnRoster" and "paulRoster" previously as

const johnRoster = $(".john-roster");
const paulRoster = $(".paul-roster");

I know I could do const allTeams = $("john-roster"),$(".paul-roster"); but since I already have these stored in variables I want to know if i can use the variables instead.

How can I do this?


Solution

  • To join two jQuery objects together you can use add():

    const $johnRoster = $(".john-roster");
    const $paulRoster = $(".paul-roster");
    
    let $allTeams = $johnRoster.add($paulRoster);
    $allTeams.on("click", function() {
      $allTeams.slideDown(400);
    });
    

    This is obviously assuming you have them selected separately already. If that's not the case you can just use a single selector:

    let $allTeams = $('.john-roster, .paul-roster');