FlyingCat
FlyingCat

Reputation: 14288

How to select the last element inside a div

I am having trouble setting my css with the image inside my div.

I have

<div class='test'>

   <a href='#'>   <img src='haha.jpg'/>   </a>
   <a href='#'>   <img src='imageINeed.jpg'/>  </a>

</div>

<div class='test'>

   <a href='#'>   <img src='haha.jpg'/>   </a>
   <a href='#'>   <img src='imageINeed1.jpg'/>  </a>

</div>

<div class='test'>

   <a href='#'>   <img src='haha.jpg'/>   </a>
   <a href='#'>   <img src='imageINeed2.jpg'/>  </a>

</div>

My jquery below will select the second image

imageSize could be varies.

  $('.test).each(function(){

        $(this).find('img:eq(1)').width(imageSize);
  })

However, there are times that I only have 1 <a> tag inside the test div.

    <div class='test'>
       <a href='#'>   <img src='imageINeed2.jpg'/>  </a>
   </div>

eq(1) won't select the img if I only have 1 <a> tag

I have tried

$('.test).each(function(){
    $(this).find('img:nth-last-child').width(imageSize);
})

It won't do it. Are there anyways to do it? Thanks so much!

Upvotes: 1

Views: 5321

Answers (1)

VisioN
VisioN

Reputation: 145478

Use :last selector:

$(".test").find("img:last").width(imageSize);

Upvotes: 7

Related Questions