Suppose I have on the catalog page there are 200 identical elements with the same class. How can I use js to add a new class through n elements. Suppose after 8, i.e. add a new class 1, 9, 17, 25 ... - element?

  • one
    Why not through CSS? - user207618 7:56 pm

4 answers 4

Without all sorts of jewels:

let elements = document.querySelectorAll('.some-class'); for (let i = 0; i < elements.length - 8; i += 8) elements[i].classList.add('another-class'); 
      var elements = document.getElementsByClassname(oneClass); for (var i=0||1||etc; i<=elements.length; i+=8) {element[i].setAttribute(class, onePerEight)}; 
    • Let me know what the setAttr method setAttr ? In JS, setAttribute ; in jQuery, attr . - user207618
    • corrected, hoped for memory, and she let him down ... - Alexey Drizhakov

    I will propose such an option, divided it in steps for understanding (you can push it up and stick it into one function)

    1 select all items

     var a = document.querySelectorAll('.card'); 

    2 select every 8th

     var b = [].filter.call(a, function(item, i){return i%8 == 0}); 

    3 assign selected class extra

     b.forEach(function(el){ el.classList.add('new-class')}); 
    • I ran: [...document.querySelectorAll('.card')].forEach((e, i) => i % 8 === 0 ? e.classList.add('some') : null) . - user207618
    • @Other +1))))) - Leonid Myronov
     var $elements = $(".odinakovyjKlass"); for (var i = 0; i < $elements.length; i = i + 8) { $elements.eq(i).addClass("drugojKlass"); } 

    @LeonidMyronov reminded about filter :

     $(".odinakovyjKlass").filter(index => !(index % 8)).addClass("drugojKlass"); 
    • ))) So I think in the right direction))) - Alexey Drizhakov