What is the correct approach to adding classes to an array of DOM objects using jQuery?

时间:2016-04-04 18:32:19

标签: jquery html css arrays dom

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?

2 个答案:

答案 0 :(得分: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.

答案 1 :(得分: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