That is an intensive overview of the jQuery.every() perform — one in every of jQuery’s most vital and most used capabilities. On this article, we’ll discover out why and try how you need to use it.
Key Takeaways
What’s jQuery.every()
jQuery’s every() perform is used to loop by every ingredient of the goal jQuery object — an object that incorporates a number of DOM parts, and exposes all jQuery capabilities. It’s very helpful for multi-element DOM manipulation, in addition to iterating over arbitrary arrays and object properties.
Along with this perform, jQuery offers a helper perform with the identical identify that may be known as with out having beforehand chosen or created any DOM parts.
jQuery.every() Syntax
Let’s see the completely different modes in motion.
The next instance selects each <div> ingredient on an online web page and outputs the index and the ID of every of them:
$('div').every(perform(index, worth) {
console.log(`div${index}: ${this.id}`);
});
A doable output could be:
div0:header
div1:major
div2:footer
This model makes use of jQuery’s $(selector).every() perform, versus the utility perform.
The following instance exhibits the usage of the utility perform. On this case the item to loop over is given as the primary argument. On this instance, we’ll present the best way to loop over an array:
const arr = [
'one',
'two',
'three',
'four',
'five'
];
$.every(arr, perform(index, worth) {
console.log(worth);
return (worth !== 'three');
});
Within the final instance, we need to reveal the best way to iterate over the properties of an object:
const obj = {
one: 1,
two: 2,
three: 3,
4: 4,
5: 5
};
$.every(obj, perform(key, worth) {
console.log(worth);
});
This all boils right down to offering a correct callback. The callback’s context, this, will likely be equal to its second argument, which is the present worth. Nonetheless, for the reason that context will at all times be an object, primitive values must be wrapped:
$.every({ one: 1, two: 2 } , perform(key, worth) {
console.log(this);
});
`
Which means there’s no strict equality between the worth and the context.
$.every({ one: 1 } , perform(key, worth) {
console.log(this == worth);
console.log(this === worth);
});
`
The primary argument is the present index, which is both a quantity (for arrays) or string (for objects).
1. Fundamental jQuery.every() Operate Instance
Let’s see how the jQuery.every() perform helps us along with a jQuery object. The primary instance selects all of the a parts within the web page and outputs their href attribute:
$('a').every(perform(index, worth){
console.log(this.href);
});
The second instance outputs each exterior href on the net web page (assuming the HTTP(S) protocol solely):
$('a').every(perform(index, worth){
const hyperlink = this.href;
if (hyperlink.match(/https?:///)) {
console.log(hyperlink);
}
});
Let’s say we had the next hyperlinks on the web page:
<a href="https://www.sitepoint.com/">SitePoint</a>
<a href="https://developer.mozilla.org">MDN net docs</a>
<a href="http://instance.com/">Instance Area</a>
The second instance would output:
https://www.sitepoint.com/
https://developer.mozilla.org/
http://instance.com/
We must always be aware that DOM parts from a jQuery object are of their “native” kind contained in the callback handed to jQuery.every(). The reason being that jQuery is actually only a wrapper round an array of DOM parts. By utilizing jQuery.every(), this array is iterated in the identical approach as an peculiar array could be. Due to this fact, we don’t get wrapped parts out of the field.
On the subject of our second instance, this implies we are able to get a component’s href attribute by writing this.href. If we needed to make use of jQuery’s attr() technique, we would wish to re-wrap the ingredient like so: $(this).attr('href').
2. jQuery.every() Array Instance
Let’s have one other take a look at how an peculiar array might be dealt with:
const numbers = [1, 2, 3, 4, 5];
$.every(numbers, perform(index, worth){
console.log(`${index}: ${worth}`);
});
This snippet outputs:
0:1
1:2
2:3
3:4
4:5
Nothing particular right here. An array options numeric indices, so we get hold of numbers ranging from 0 and going as much as N-1, the place N is the variety of parts within the array.
3. jQuery.every() JSON Instance
We might have extra difficult information buildings, reminiscent of arrays in arrays, objects in objects, arrays in objects, or objects in arrays. Let’s see how jQuery.every() may help us in such eventualities:
const colours = [
{ 'red': '#f00' },
{ 'green': '#0f0' },
{ 'blue': '#00f' }
];
$.every(colours, perform() {
$.every(this, perform(identify, worth) {
console.log(`${identify} = ${worth}`);
});
});
This instance outputs:
purple =
inexperienced =
blue =
We deal with the nested construction with a nested name to jQuery.every(). The outer name handles the array of the variable colours; the inside name handles the person objects. On this instance every object has just one key, however normally, any quantity might be tackled with this code.
4. jQuery.every() Class Instance
This instance exhibits the best way to loop by every ingredient with assigned class productDescription given within the HTML beneath:
<div class="productDescription">Crimson</div>
<div>Pink</div>
<div class="productDescription">Orange</div>
<div class="generalDescription">Teal</div>
<div class="productDescription">Inexperienced</div>
We use the every() helper as a substitute of the every() technique on the selector.
$.every($('.productDescription'), perform(index, worth) {
console.log(index + ':' + $(worth).textual content());
});
On this case, the output is:
0:Crimson
1:Orange
2:Inexperienced
We don’t have to incorporate index and worth. These are simply parameters that assist decide which DOM ingredient we’re presently iterating on. Moreover, on this situation we are able to additionally use the extra handy every technique. We are able to write it like this:
$('.productDescription').every(perform() {
console.log($(this).textual content());
});
And we’ll get hold of this on the console:
Crimson
Orange
Inexperienced
Notice that we’re wrapping the DOM ingredient in a brand new jQuery occasion, in order that we are able to use jQuery’s textual content() technique to acquire the ingredient’s textual content content material.
5. jQuery.every() Delay Instance
Within the subsequent instance, when the person clicks the ingredient with the ID 5demo all record gadgets will likely be set to orange instantly.
<ul id="5demo">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>4</li>
<li>5</li>
</ul>
After an index-dependent delay (0, 200, 400, … milliseconds) we fade out the ingredient:
$('#5demo').on('click on', perform(e) {
$('li').every(perform(index) {
$(this).css('background-color', 'orange')
.delay(index * 200)
.fadeOut(1500);
});
e.preventDefault();
});
Conclusion
On this publish, we’ve demonstrated the best way to use the jQuery.every() perform to iterate over DOM parts, arrays and objects. It’s a robust and time-saving little perform that builders ought to have of their toolkits.
And if jQuery isn’t your factor, you would possibly need to take a look at utilizing JavaScript’s native Object.keys() and Array.prototype.forEach() strategies. There are additionally libraries like foreach which allow you to iterate over the important thing worth pairs of both an array-like object or a dictionary-like object.
Keep in mind: $.every() and $(selector).every() are two completely different strategies outlined in two other ways.
This in style article was up to date in 2020 to mirror present greatest practices and to replace the conclusion’s recommendation on native options utilizing trendy JavaScript. For extra in-depth JavaScript information, learn our ebook, JavaScript: Novice to Ninja, 2nd Version.
FAQs on jQuery’s every() Operate
.every() perform in jQuery?
The .every() perform is utilized in jQuery to iterate by a set of DOM parts and carry out a selected motion on every ingredient.
.every() perform in jQuery?
You should use the .every() perform by choosing a set of parts with a jQuery selector, after which calling .every() on that choice. You present a callback perform that defines the motion to be carried out on every ingredient.
.every()?
The callback perform accepts two parameters: index (the present index of the ingredient within the assortment) and ingredient (the present DOM ingredient being iterated over).
index parameter within the .every() callback perform?
You should use the index parameter to maintain monitor of the present ingredient’s place within the assortment, which might be helpful for conditional actions or different operations.
.every() perform?
Frequent use circumstances embody iterating by an inventory of parts to govern their properties, values, or types, and performing customized actions on every ingredient in a set.


