Home > OS >  loop or each? or other jQuery solution?
loop or each? or other jQuery solution?

Time:01-19

How can I simplify the code below into just one element? Hoe can I avoid repetition for each function?

$('#pane-A .accordion.tabs').each(function() {
  if ($(this).length > 3)
    return;
  $('#pane-A .accordion.tabs:gt(2)').hide();
});

$('#pane-B .accordion.tabs').each(function() {
  if ($(this).length > 3)
    return;
  $('#pane-B .accordion.tabs:gt(2)').hide();
});

$('#pane-C .accordion.tabs').each(function() {
  if ($(this).length > 3)
    return;
  $('#pane-C .accordion.tabs:gt(2)').hide();
});

$('#pane-D .accordion.tabs').each(function() {
  if ($(this).length > 3)
    return;
  $('#pane-D .accordion.tabs:gt(2)').hide();
});

$('#pane-E .accordion.tabs').each(function() {
  if ($(this).length > 3)
    return;
  $('#pane-E .accordion.tabs:gt(2)').hide();
});

CodePudding user response:

Put a common class on all the #pane-X elements. Then you can loop through them in a single each() statement using find() to get the related elements to hide.

Also note that the if statement is largely redundant, as jQuery functions are tolerant of missing elements, also that the :gt() selector is deprecated. Use slice() instead.

With that said, the code can be reduced to just the following for all instances:

$('.pane').each(function() {
  $(this).find('.accordion.tabs').slice(3).hide();
});
.pane { margin: 10px 0; } /* just for demo purposes */
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div  id="pane-A">
  Pane A
  <div >Tab 1</div>
  <div >Tab 2</div>
  <div >Tab 3</div>
  <div >Tab 4</div>
  <div >Tab 5</div>
  <div >Tab 6</div>
</div>
<div  id="pane-B">
  Pane B
  <div >Tab 1</div>
  <div >Tab 2</div>
</div>
<div  id="pane-C">
  Pane C
  <div >Tab 1</div>
  <div >Tab 2</div>
  <div >Tab 3</div>
  <div >Tab 4</div>
  <div >Tab 5</div>
  <div >Tab 6</div>
</div>

CodePudding user response:

Something like this could work.

    $('#pane-A, #pane-B, #pane-C, #pane-D, #pane-E').each(function() {
        let tabs = $('.accordion.tabs', this);
        if (tabs.length > 3) return;
        $('.accordion.tabs:gt(2)', this).hide();
    }

  •  Tags:  
  • Related