Michelle
Michelle

Reputation: 1844

Add count of contained divs within each div via jQuery

This seems like it should work but for some reason it isn't. Can anyone help?

I am trying to add the count of children divs to the "booklist" divs on this page: http://216.172.167.18/~julia/books/

I have this jQuery running:

$('.booklist').addClass(function() {
        return $(this).children('div').length;
    });

Thanks for your help! Michelle

Upvotes: 0

Views: 163

Answers (2)

Sander
Sander

Reputation: 13431

you better use each to get to your expected behaviour. the .addClass() takes a string.

work around it trough the .each();

$('.booklist').each(function() {
    $(this).addClass($(this).children('div').length.toString());
});

demo: http://jsfiddle.net/saelfaer/jNks3/1/

EDIT keep in mind that the .addClass() function takes a function or a string... not an integer. so a mere .toString() fixes that.

Upvotes: 1

aziz punjani
aziz punjani

Reputation: 25776

Length is a number, it needs to be a string.

$('.booklist').addClass(function() {
    return $(this).children('div').length.toString();
});

Upvotes: 5

Related Questions