0

So I would like to simply input array inside jquery. Result I want to achieve is this:

$(".game-board, .building-tokens").click( function() {
    $( ".mission-cards, .game-board, .building-costs, .mission-cards, .resources-cards, .resources-tokens, .road-card, .game-modal, .dice" ).toggleClass( "game-opacity" );
});

But this code is a way too long. And there must be more reasonable solution. So I try to put all the css classes inside an array like this:

var classes = [".game-board", ".building-tokens", ".mission-cards", ".building-tokens", ".building-costs", ".mission-cards", ".resources-cards", ".resources-tokens", ".road-card", ".game-modal", ".dice"];

$(".game-board, .building-tokens").click( function() {
    $('"' + classes.toString() + '"').toggleClass( "game-opacity" );
});

Why this code doesn't work?

2
  • 1
    Don't need extra quotes, use $(classes.join('')).toggleClass("game-opacity"); Commented Dec 11, 2015 at 9:58
  • You can iterate through each element of array using .each() function. Commented Dec 11, 2015 at 10:00

1 Answer 1

1

You can use join() method of array to join all elements and then

$(classes.join()).toggleClass("game-opacity")
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You! Worked like a charm :) Tushar was also correct, execept there should be ".join()", instead of ".join('')"

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.