2

I have a list of elements:

<ul id="wpsl-stores">
    <li>list</li>
    <li>list</li>
    <li class="skipthis">list</li>
    <li>list</li>
    <li>list</li>
    <li>list</li>
    <li class="skipthis">list</li>
    <li>list</li>
</ul>

I'm looping through the elements and appending the number of that element:

var locCount = $('#wpsl-stores li').length;


for (i = 1; i < locCount+1; i++) {

    $('#wpsl-stores ul li:nth-child('+i+') strong:before').hide();

    $('body').append('<style>#wpsl-stores ul li:nth-child('+i+') strong:before {content:"'+i+'";}</style>');    

}

I need to skip the elements that have the "skipthis" class.

On the actual site, the elements with the "skipthis" class are hidden but still in the dom. This means the loop above is still counting them.

Right now, the output is something like this: 1 list 2 list 4 list 5 list 6 list etc. etc.

I need it to be 1 list 2 list 3 list 4 list

user715564
  • 1,650
  • 2
  • 25
  • 60
  • I would grab the li elements, and then use the hasClass to check if they are skipThis and splice them out. – Ryan Wilson Feb 01 '18 at 20:39
  • Possible duplicate of [jQuery .hasClass() vs .is()](https://stackoverflow.com/questions/4901553/jquery-hasclass-vs-is) – AGoranov Feb 01 '18 at 20:39

4 Answers4

0

How about:

for (i = 1; i < locCount+1; i++) {
  var $listElt = $('#wpsl-stores ul li:nth-child('+i+') strong:before');
  if (!$listElt.hasClass('skipThis') {
    $listElt.hide();

    $('body').append('<style>#wpsl-stores ul li:nth-child('+i+') strong:before {content:"'+i+'";}</style>');    
  }
}

reference

nvioli
  • 4,137
  • 3
  • 22
  • 38
0

try adding .not

$('#wpsl-stores li').not( ".skipthis" )

source: http://api.jquery.com/not/

gwalshington
  • 1,418
  • 2
  • 30
  • 60
0

You should select all the elements that aren't skipthis and loop through to add:

$('#wpsl-stores li:not(.skipthis)').each(function(i,li) {
   $('body').append('<style>#wpsl-stores ul li:nth-child('+(i+1)+') strong:before {content:"'+(i+1)+'";}</style>');
});

EDIT: If you want to remove the skipthis ones and add a counter to the others:

var listCount = 0;
$('#wpsl-stores li').each(function(i,li) {
   if ($(this).hasClass('skipthis')) {
      $(this).remove();
   } else {
      listCount++;   
      $('body').append('<style>#wpsl-stores ul li:nth-child('+listCount+') strong:before {content:"'+listCount+'";}</style>');
   }
});
fanfavorite
  • 5,128
  • 1
  • 31
  • 58
0

You can use .each() for iteration and .hasClass() to skip some li elements:

$("#wpsl-stores li").each(function (index, element) {
   if (!$(element).hasClass('skipthis')) {
      // do something
   }
});
DenysM
  • 389
  • 1
  • 2
  • 13