2

I have tried two types of iterating techniques but both produce the same error:

addClass is not function

First example using for:

function game(){
    var cards = $('.card');

    function initialize(){
        for(var x = 0; x < cards.length; x++) {    
            cards[x].addClass('wtf');    
        }
    };
};

Second try using each:

function game(){
    var cards = $('.card');

    function initialize(){
        //Add random key values to pairs of cards
        $.each( cards ,function(i, ele) {    
            ele[i].addClass('wtf');
        });
    };
};

What is the correct way to manipulate these type of arrays?

1
  • What about $('.card').addClass('wtf'); jQuery goes through each one for you, you don't have to. Am I missing something? Commented Apr 4, 2016 at 20:28

2 Answers 2

7

Your code examples don't work as you're attempting to call a jQuery method, addClass, on a DOMElement instead of a jQuery object.

The addClass() method will do the looping for you internally if multiple elements match the selector in the jQuery object so it's just a one-line call you need to make:

function game(){
    var $cards = $('.card');

    function initialize() {
        $cards.addClass('wtf');
    };
};

How would I be able to select the 5th card for example and add the class to only that card?

To do that you can use the eq() method:

$cards.eq(4).addClass('wtf');

Note that the index is zero based, hence the 5th element is index 4.

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

2 Comments

Thanks! The above example adds the 'wtf' class to all DOMElements in the array. However how would I be able to select the 5th card for example and add the class to only that card?
You can use the eq() method to do that: $cards.eq(4).addClass('wtf'); I updated the answer for you.
1

cards[x] is a DOM element, use $(cards[x]) jQuery object like following.

function game() {
    var cards = $('.card');

    function initialize() {
        for (var x = 0; x < cards.length; x++) {
            //change following line. 
            $(cards[x]).addClass('wtf');
        }
    };
};

You don't need to loop through all element. You cant just use cards .addClass('wtf') like following.

function game() {
    var cards = $('.card');

    function initialize() { 
        cards.addClass('wtf');
    };
};

If you want select specific card then use eq() method like following.

cards.eq(4).addClass('wtf');   //eq(4) will select 5th card

1 Comment

Thanks Azim it looks like I can use that with a for loop to select a specific card.

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.