Saturday, March 16, 2024

5 jQuery.every() Operate Examples — SitePoint

Must read


That is an intensive overview of the jQuery.every() perform — considered one of jQuery’s most essential and most used capabilities. On this article, we’ll discover out why and try how you should use it.

Key Takeaways

  1. The jQuery.every() perform is a flexible instrument in jQuery for iterating over DOM parts, arrays, and objects, permitting for environment friendly multi-element DOM manipulation and knowledge processing.
  2. The perform offers two modes of operation: as a technique referred to as on a jQuery object for DOM parts and as a utility perform for arrays and objects, with every mode catering to various kinds of knowledge constructions.
  3. By way of sensible examples, the article showcases the ability and adaptability of jQuery.every(), emphasizing its significance in simplifying the iteration course of and highlighting various JavaScript strategies for comparable duties.

What’s jQuery.every()

jQuery’s every() perform is used to loop by means of every component of the goal jQuery object — an object that comprises 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 title that may be referred to 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> component 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 attainable output could be:

div0:header
div1:principal
div2:footer

This model makes use of jQuery’s $(selector).every() perform, versus the utility perform.

The subsequent instance reveals the usage of the utility perform. On this case the article to loop over is given as the primary argument. On this instance, we’ll present easy methods 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 exhibit easy methods 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 all the way down to offering a correct callback. The callback’s context, this, will likely be equal to its second argument, which is the present worth. Nevertheless, because the context will all the time be an object, primitive values need to 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 at the side of 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 internet 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 should always be aware that DOM parts from a jQuery object are of their “native” type 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 bizarre array could be. Subsequently, we don’t get wrapped parts out of the field.

With 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 component like so: $(this).attr('href').

2. jQuery.every() Array Instance

Let’s have one other have a look at how an bizarre array may 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 sophisticated knowledge constructions, akin 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(title, worth) {
    console.log(`${title} = ${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 interior name handles the person objects. On this instance every object has just one key, however normally, any quantity could possibly be tackled with this code.

4. jQuery.every() Class Instance

This instance reveals easy methods to loop by means of every component 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 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:Purple
1:Orange
2:Inexperienced

We don’t have to incorporate index and worth. These are simply parameters that assist decide which DOM component 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 get hold of this on the console:

Purple
Orange
Inexperienced

Notice that we’re wrapping the DOM component in a brand new jQuery occasion, in order that we are able to use jQuery’s textual content() technique to acquire the component’s textual content content material.

5. jQuery.every() Delay Instance

Within the subsequent instance, when the consumer clicks the component with the ID 5demo all listing 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 component:

$('#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 easy methods 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 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.

Bear in mind: $.every() and $(selector).every() are two completely different strategies outlined in two other ways.

This fashionable article was up to date in 2020 to replicate present greatest practices and to replace the conclusion’s recommendation on native options utilizing fashionable JavaScript. For extra in-depth JavaScript data, learn our e book, JavaScript: Novice to Ninja, 2nd Version.

FAQs on jQuery’s every() Operate

What’s the function of the .every() perform in jQuery?

The .every() perform is utilized in jQuery to iterate by means of a group of DOM parts and carry out a selected motion on every component.

How do I exploit the .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 component.

What are the parameters of the callback perform used with .every()?

The callback perform accepts two parameters: index (the present index of the component within the assortment) and component (the present DOM component being iterated over).

How can I exploit the index parameter within the .every() callback perform?

You should use the index parameter to maintain observe of the present component’s place within the assortment, which may be helpful for conditional actions or different operations.

What are some widespread use instances for the .every() perform?

Frequent use instances embody iterating by means of an inventory of parts to govern their properties, values, or types, and performing customized actions on every component in a group.



Supply hyperlink

More articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest article