Find nearest element

javascript, jquery

Solution

You can try this with `.nextAll()` and `:first`:

    $('article').on('click', function () {
         $('.load-work').each(function () {
               $(this).hide().removeClass('loaded-work').html('');
         });
         $(this).nextAll('.load-work:first').show().addClass('loaded-work');
    });

Fiddle

Or better one:

  $('article').on('click', function () {
       $('.load-work').each(function () {
           $(this).hide().removeClass('loaded-work').html('');
       });
       if($(this).nextAll('.load-work:first').length){
           $(this).nextAll('.load-work:first').show().addClass('loaded-work');
       }else{
           $(this).prevAll('.load-work:first').show().addClass('loaded-work');
       }
   });

Updated fiddle

Problem

I have this html: ``` <div class="row"> <article>1</article> <article>2</article> <div class="load-work"></div> <article>3</article> <article>4</article> <div class="load-work"></div> <article>5</article> <article>6</article> </div> ``` What I want to do is to find nearest `.load-work` to clicked `article`. My current JS is: ``` $('article').each(function() { $(this).on('click', function() { $('.load-work').each(function() { $(this).hide().removeClass('loaded-work').html(''); }); $(this).closest('.row').find('.load-work').show().addClass('loaded-work') }) }); ``` But it doesn't work - it finds each. Here's jsfiddle

Original source