Evanss
Evanss

Reputation: 23563

Combine this JS to use a single selector?

With the following Im getting the first 3 div.selector and removing the hidden class, and im also applying a function to the image thats within them.

    $(".selector").slice(0, 3).removeClass('hidden');

    $(".selector").slice(0, 3).find('img').each(imgFunction);

How can I rewrite this to be a single selector? My code works but it seems a bit clumsy.

Upvotes: 0

Views: 38

Answers (3)

Evanss
Evanss

Reputation: 23563

    $(".selector").slice(0, 3).removeClass('hidden').find('img').each(showImg);

You can simply 'chain' removeClass and the other functions.

Upvotes: 0

Giuseppe Silvano
Giuseppe Silvano

Reputation: 151

removeClass returns the jQuery object, so you can chain your calls this way:

$(".selector")
  .slice(0, 3)
  .removeClass("hidden")
  .find("img")
  .each(imgFunction);

Upvotes: 4

ArinCool
ArinCool

Reputation: 1738

Or, you can try this cleaner statement:

$(".selector:lt(4)").removeClass('hidden').find('img').each(imgFunction);

Upvotes: 1

Related Questions