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 ></div>
<div ></div>
<div ></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.
CodePudding user response:
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;
}
CodePudding user response:
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 >1</div>
<div >2</div>
<div >3</div>