Search code examples
jqueryfindparent

Access once to the child and then reuse the parent in jQuery (1.9.x and more)


I'm looking a better to do this job, I would like to fill the caption of the image clicked, and I am sure there is a better solution.

Thanks for your answers, Allan. (fr)

Jquery is :

$bImg
  .find('.title, .caption')
    .fadeIn()
  .parent()
  .find('.title')
    .text(title)
  .parent()
  .find('.caption')
    .text(caption);

The HTML is:

<div class="big-image carousel">
   <img src="http://placehold.it/450x240/FFFFCC">
   <div class="title">ThIs PhOtO</div>
   <div class="caption">Itaque earum rerum hic in tenetur</div>
</div>

PS : $bImg = $('.big-image');


Solution

  • You can use .filter() and .siblings()

    $bImg
      .find('.title, .caption')
        .fadeIn()
      .filter('.title') // gets .title out of the collection
        .text(title)
      .siblings('.caption')
        .text(caption);