1
2
3<...">

Find the closest item

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 find the closest .load-workto click article. My current JS:

$('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 that will not work - he finds everyone. Here jsfiddle

+4
source share
2 answers

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:

  $('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

+4
source

Use the following

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

Working fiddle => http://jsfiddle.net/naw8W/3/

0
source

Source: https://habr.com/ru/post/1533907/


All Articles