Reputation:
These are some basic ways I have used to declare an jquery object while looping:
let $divs = $('.mydiv');
for (let i = 0; i < $divs.length; i++) {
let $div = $($divs[i]);
}
// or
for (let $div of Array.from($divs)) {
$div = $($div);
}
// or
Array.from($divs).forEach(function ($div) {
$div = $($div);
});
I want to save the line $div = $($div)
(for writing code faster), like these:
for (let $($div) of Array.from($divs)) {
// ...
}
// or
Array.from($divs).forEach(function ($div = $($div)) {
// ...
});
Is there a way to achieve my goal?
UPDATE:
Because $('.mydiv')
can return more than 1 element, so I need a loop to work with them. But using a loop, it doesn't return an jquery object for per element, I have to wrap it by $(...)
Upvotes: 0
Views: 89
Reputation: 135396
Not really an answer to not really a question
After you have an array of $
-wrapped elements, what do you plan on doing with it?
$('.mydiv') // = $-wrapped html collection
.map((_, e) => $(e)) // = array of $-wrapped elements
.each((_, e) => console.log(e)) // = log each $-wrapped element
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mydiv">1</div>
<div class="mydiv">2</div>
<div class="mydiv">3</div>
That's really no different than this script below, so what's the point?
$('.mydiv') // = $-wrapped html collection
.each((_, e) => console.log($(e))) // = log each $-wrapped element
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mydiv">1</div>
<div class="mydiv">2</div>
<div class="mydiv">3</div>
Upvotes: 1