Legionar Legionar - 9 days ago 6
jQuery Question

Insert div after closest sibling with specified class

I have code like this:

<div class="container">
<div class="row">
<div class="col-xs-6 col-sm-3 col-md-2 prcolor">Test</div>
<div class="col-xs-6 col-sm-3 col-md-2 prcolor">Test</div>
<div class="clearfix visible-xs"></div>
<div class="col-xs-6 col-sm-3 col-md-2 prcolor">Test</div>
<div class="col-xs-6 col-sm-3 col-md-2 prcolor">Test</div>
<div class="clearfix visible-sm"></div>
<div class="clearfix visible-xs"></div>
<div class="col-xs-6 col-sm-3 col-md-2 prcolor">Test</div>
<div class="col-xs-6 col-sm-3 col-md-2 prcolor">Test</div>
<div class="clearfix visible-lg"></div>
<div class="clearfix visible-md"></div>
<div class="clearfix visible-xs"></div>
</div>
</div>


And when I click on div with class
prcolor
, I want to insert new div after closest sibling with class
visible-xs
.

I tried
$.next('.visible-xs')
,
$.closest('.visible-xs')
,
$.siblings('.visible-xs')
,
$.nextAll('.visible-xs')
, but as I read, the selector is accepted only if function can't found element in DOM.

$('.prcolor').on('click', function() {
$(this).nextAll('.visible-xs').after('<div>Inserted div</div>');
});


But this is doing nothing and the div is not inserted after. Where am I wrong?

Example of expected after clicking on first
.prcolor
:

<div class="container">
<div class="row">
<div class="col-xs-6 col-sm-3 col-md-2 prcolor">Test</div>
<div class="col-xs-6 col-sm-3 col-md-2 prcolor">Test</div>
<div class="clearfix visible-xs"></div>
<div>Inserted div</div>
<div class="col-xs-6 col-sm-3 col-md-2 prcolor">Test</div>
<div class="col-xs-6 col-sm-3 col-md-2 prcolor">Test</div>
<div class="clearfix visible-sm"></div>
<div class="clearfix visible-xs"></div>
<div class="col-xs-6 col-sm-3 col-md-2 prcolor">Test</div>
<div class="col-xs-6 col-sm-3 col-md-2 prcolor">Test</div>
<div class="clearfix visible-lg"></div>
<div class="clearfix visible-md"></div>
<div class="clearfix visible-xs"></div>
</div>
</div>


DEMO

Thanks.

Answer

If you want to match nearest following sibling with specific class, you can use $.fn.nextAll() chained with $.fn.first(). e.g:

$('.prcolor').on('click', function() {
  $(this).nextAll('.visible-xs').first().after('<div>INSERTED</div>');
});