skip to Main Content

I’m trying to translate my jquery code into vanilla js.
this piece of code:

let count = 1;
        $($(".card").get().reverse()).each(function () {
            $(this).addClass("zIndex" + count);
            count++;
        });

basically i have a bunch of divs with class .card, for each of these i need to assign the class zIndex with a decreasing number, so that it comes out like this:

<div class="card zIndex3"></div>
<div class="card zIndex2"></div>
<div class="card zIndex1"></div>

I’m going to be honest, i have no clue where to start, especially regarding the $($(".card").get().reverse())

any help or even clues on how to proceed is greatly appreciated.

2

Answers


  1. One alternative to get() method in jquery is querySelectorAll with javascript.

    const cards = document.querySelectorAll('.card');
    

    And equalized to reverse is creating a decreasing loop start from last index of the cards and end with index equal to zero.

    for (let i = cards.length - 1; i >= 0; i--) {
       const card = cards[i];
       cards.style.zIndex = i;
    }
    
    Login or Signup to reply.
  2. you can use the array.reverse method in js https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse

    and to translate the jquery loop you have, you can :

    • create an array with document.querySelectorAll and [...data] syntax
    • directly call reverse on this array

    [...document.querySelectorAll('.card')].reverse()

    // in jquery
    let count = 1;
    $($(".card").get().reverse()).each(function() {
      console.log($(this).text());
    });
    
    console.log('*******************');
     
     // without jquery
     count = 1;
    [...document.querySelectorAll('.card')].reverse().forEach(elem => {
      console.log(elem.innerText);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="card zIndex3">1</div>
    <div class="card zIndex2">2</div>
    <div class="card zIndex1">3</div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search