Backslash
Backslash

Reputation: 353

Getting the amount of images which are in a specific div

I'm trying to get the amount of images which are stored in the post-content container of each post.

The layout of a post looks like this:

<div class="post">
  <div class="post-toolbar">
    <div class="post-date">date</div>
    <div class="signs">
      <div class="hearts">&hearts;</div>
      <div><img src="logo.png"></div>
      <div><img src="logo2.png"></div>
    </div>
    <div class="post-title">title</div>
  </div>

  <div class="post-content">
    <a href="#link"><img src="image.png"></a>
    <a href="#link"><img src="image.png"></a>
  </div>
</div>

And a Javascript snippet which looks like this:

$('.hearts').live("click",function() {
    var amount = $(this).parent().parent().parent().find("img").size();
    console.log(amount);        
});

At the moment the value of amount is 4.

I'm sure the is a much nicer way to access the .post-content div with jQuery.

Upvotes: 3

Views: 119

Answers (2)

PeeHaa
PeeHaa

Reputation: 72672

$('.hearts').live("click",function() {
    var post = $(this).closest('.post'); // will find the first element with the class post up the DOM tree
    var amount = $('.post-content img', post).size();
    console.log(amount);        
});

BTW you should really look into .delegate() and never use .live() again since live is way slower than delegate.

Or even better if you are on jQuery 1.7 or higher use .on().

Upvotes: 2

ijse
ijse

Reputation: 3035

How about $(this).parents(".post") ?

$('.hearts').live("click",function() {
    var amount = $(this).parents(".post").children(".post-content").find("img").size();
    alert(amount);       
});

Upvotes: 2

Related Questions