That is an intensive overview of the jQuery.every()
perform — one in every of jQuery’s most necessary and most used capabilities. On this article, we’ll discover out why and try how you should utilize it.
Key Takeaways
What’s jQuery.every()
jQuery’s each() function is used to loop by way of every aspect of the goal jQuery object — an object that comprises a number of DOM components, 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 supplies a helper perform with the identical identify that may be known as with out having beforehand chosen or created any DOM components.
jQuery.every() Syntax
Let’s see the totally different modes in motion.
The next instance selects each <div>
aspect on an internet 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 can be:
div0:header
div1:primary
div2:footer
This model makes use of jQuery’s $(selector).every()
perform, versus the utility perform.
The following instance reveals the usage of the utility perform. On this case the thing to loop over is given as the primary argument. On this instance, we’ll present how one can 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 display how one can 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
, might be equal to its second argument, which is the present worth. Nonetheless, because the context will all the time be an object, primitive values must be wrapped:
$.every({ one: 1, two: 2 } , perform(key, worth) {
console.log(this);
});
`
Which means that 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 at the side of a jQuery object. The primary instance selects all of the a
components 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 internet 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.Pylogix.com/">Pylogix</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.Pylogix.com/
https://developer.mozilla.org/
http://instance.com/
We must always notice that DOM components from a jQuery object are of their “native” kind contained in the callback handed to jQuery.every()
. The reason being that jQuery is in reality only a wrapper round an array of DOM components. Through the use of jQuery.every()
, this array is iterated in the identical method as an atypical array can be. Subsequently, we don’t get wrapped components out of the field.
As regards to our second instance, this implies we are able to get a component’s href
attribute by writing this.href
. If we wished to make use of jQuery’s attr()
technique, we would wish to re-wrap the aspect like so: $(this).attr('href')
.
2. jQuery.every() Array Instance
Let’s have one other have a look at how an atypical array will 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 receive numbers ranging from 0 and going as much as N-1, the place N is the variety of components within the array.
3. jQuery.every() JSON Instance
We could have extra difficult knowledge buildings, comparable to arrays in arrays, objects in objects, arrays in objects, or objects in arrays. Let’s see how jQuery.every()
can assist us in such situations:
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 internal name handles the person objects. On this instance every object has just one key, however usually, any quantity could possibly be tackled with this code.
4. jQuery.every() Class Instance
This instance reveals how one can loop by way of every aspect with assigned class productDescription
given within the HTML beneath:
<div class="productDescription">Purple</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 an alternative 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:Purple
1:Orange
2:Inexperienced
We don’t have to incorporate index and worth. These are simply parameters that assist decide which DOM aspect we’re at the moment iterating on. Moreover, on this state of affairs 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 receive this on the console:
Purple
Orange
Inexperienced
Observe that we’re wrapping the DOM aspect in a brand new jQuery occasion, in order that we are able to use jQuery’s text()
method to acquire the aspect’s textual content content material.
5. jQuery.every() Delay Instance
Within the subsequent instance, when the consumer clicks the aspect with the ID 5demo
all listing gadgets might 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 aspect:
$('#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 submit, we’ve demonstrated how one can use the jQuery.every()
perform to iterate over DOM components, arrays and objects. It’s a strong and time-saving little perform that builders ought to have of their toolkits.
And if jQuery isn’t your factor, you may need to have 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 totally different strategies outlined in two other ways.
This well-liked article was up to date in 2020 to mirror present greatest practices and to replace the conclusion’s recommendation on native options utilizing fashionable JavaScript. For extra in-depth JavaScript data, learn our ebook, JavaScript: Novice to Ninja, 2nd Edition.
FAQs on jQuery’s every()
Operate
.every()
perform in jQuery?The .every()
perform is utilized in jQuery to iterate by way of a set of DOM components and carry out a selected motion on every aspect.
.every()
perform in jQuery?You should utilize the .every()
perform by choosing a set of components 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 aspect.
.every()
?The callback perform accepts two parameters: index
(the present index of the aspect within the assortment) and aspect
(the present DOM aspect being iterated over).
index
parameter within the .every()
callback perform?You should utilize the index
parameter to maintain observe of the present aspect’s place within the assortment, which will be helpful for conditional actions or different operations.
.every()
perform?Widespread use instances embody iterating by way of a listing of components to control their properties, values, or types, and performing customized actions on every aspect in a set.