Alex
Alex

Reputation: 68104

jQuery - select groups of child elements based on the parent DIV element

I have a normal html page with stuff like divs and links with images:

<div>
  <a href="foo.jpg"> ... </a>
  <a href="boo.jpg"> ... </a>
</div>

<div>
  <a href="bah.jpg"> ... </a>
  <a href="gah.jpg"> ... </a>
</div>

...

I'm trying to hook a lightbox script on all links that end with jpg/gif/png extensions.

Right now, based on a previous question I asked :), I have:

 $('div a').filter(function(){
   return this.href.match('[\.jpg|\.png|\.gif]$');
 }).colorbox({
   rel: 'gallery'
 });

which groups all links inside gallery.

But I would want to group links from each div inside their own gallery. For example .foo' & .boo links inside a gallery1 and .bah & .gah inside gallery2 and so on...

How can I do that?

Upvotes: 3

Views: 1782

Answers (2)

user578895
user578895

Reputation:

(sorry, can't comment on the other answer)

Your regex needs parentheses, not brackets:

(\.jpg|\.png|\.gif)$

otherwise you're literally matching the characters .jpgpnif| and a filename of foo| matches.

Upvotes: 2

Richard Dalton
Richard Dalton

Reputation: 35793

$('div').each(function(index) {
   $(this).find('a').filter(function(){
       return this.href.match('[\.jpg|\.png|\.gif]$');
   }).colorbox({
       rel: 'gallery' + index
   });
});

Upvotes: 8

Related Questions