Monday, February 3, 2020

5 jQuery.each() Function Examples

5 jQuery.each() Function Examples

This is an extensive overview of the jQuery.each() function — one of jQuery’s most important and most used functions. In this article, we’ll find out why and take a look at how you can use it.

What is jQuery.each()

jQuery’s each() function is used to loop through each element of the target jQuery object — an object that contains one or more DOM elements, and exposes all jQuery functions. It’s very useful for multi-element DOM manipulation, as well as iterating over arbitrary arrays and object properties.

In addition to this function, jQuery provides a helper function with the same name that can be called without having previously selected or created any DOM elements.

jQuery.each() Syntax

Let’s see the different modes in action.

The following example selects every <div> element on a web page and outputs the index and the ID of each of them:

// DOM ELEMENTS
$('div').each(function(index, value) {
  console.log(`div${index}: ${this.id}`);
});

A possible output would be:

div0:header
div1:main
div2:footer

This version uses jQuery’s $(selector).each() function, as opposed to the utility function.

The next example shows the use of the utility function. In this case the object to loop over is given as the first argument. In this example, we'll show how to loop over an array:

// ARRAYS
const arr = [
  'one',
  'two',
  'three',
  'four',
  'five'
];

$.each(arr, function(index, value) {
  console.log(value);
  // Will stop running after "three"
  return (value !== 'three');
});

// Outputs: one two three

In the last example, we want to demonstrate how to iterate over the properties of an object:

// OBJECTS
const obj = {
  one: 1,
  two: 2,
  three: 3,
  four: 4,
  five: 5
};

$.each(obj, function(key, value) {
  console.log(value);
});

// Outputs: 1 2 3 4 5

This all boils down to providing a proper callback. The callback’s context, this, will be equal to its second argument, which is the current value. However, since the context will always be an object, primitive values have to be wrapped:

$.each({ one: 1, two: 2 } , function(key, value) {
  console.log(this);
});

// Number { 1 }
// Number { 2 }

`

This means that there's no strict equality between the value and the context.

$.each({ one: 1 } , function(key, value) {
  console.log(this == value);
  console.log(this === value);
});

// true
// false

`

The first argument is the current index, which is either a number (for arrays) or string (for objects).

1. Basic jQuery.each() Function Example

Let’s see how the jQuery.each() function helps us in conjunction with a jQuery object. The first example selects all the a elements in the page and outputs their href attribute:

$('a').each(function(index, value){
  console.log(this.href);
});

The second example outputs every external href on the web page (assuming the HTTP(S) protocol only):

$('a').each(function(index, value){
  const link = this.href;

  if (link.match(/https?:\/\//)) {
    console.log(link);
  }
});

Let’s say we had the following links on the page:

<a href="https://www.sitepoint.com/">SitePoint</a>
<a href="https://developer.mozilla.org">MDN web docs</a>
<a href="http://example.com/">Example Domain</a>

The second example would output:

https://www.sitepoint.com/
https://developer.mozilla.org/
http://example.com/

We should note that DOM elements from a jQuery object are in their "native" form inside the callback passed to jQuery.each(). The reason is that jQuery is in fact just a wrapper around an array of DOM elements. By using jQuery.each(), this array is iterated in the same way as an ordinary array would be. Therefore, we don’t get wrapped elements out of the box.

With reference to our second example, this means we can get an element's href attribute by writing this.href. If we wanted to use jQuery's attr() method, we would need to re-wrap the element like so: $(this).attr('href').

The post 5 jQuery.each() Function Examples appeared first on SitePoint.


by Florian Rappl via SitePoint

The Money Being Spent on Social Media Creators: An Inside Look Sponsored Content Rates

Perhaps one of the biggest examples of a new form of career that has arisen over the past decade is content creation. You see, with platforms like YouTube gaining momentum as well as highly accessible it finally became popular for people to start looking into making some actual content that...

[ This is a content summary only. Visit our website https://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Zia Muhammad via Digital Information World

Microsoft's LinkedIn Breaks Engagement and Member Count Records

Perhaps the most prominent dark horse as far as the various social media platforms of the past decade are concerned is quite possibly LinkedIn. It started out as a company that you would get annoying emails about when people you knew would send requests that you would inevitably ignore, but over...

[ This is a content summary only. Visit our website https://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Zia Muhammad via Digital Information World

Apple engineers want to make two-factor authentication easier

On many secure websites, users often come across one-time passcode (OTP). A security system that sends a message of unique code to the user's device (usually on a smartphone), which they use on the website to verify themselves. While it's a secure way, many users find it a bit frustrating and hard...

[ This is a content summary only. Visit our website https://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Abdullah Matloob via Digital Information World

How to Use Instagram Customer Reviews for Maximum Impact

Are you taking full advantage of glowing reviews from your best customers? Looking for actionable ways to increase your social proof on Instagram? In this article, you’ll learn how to leverage customer testimonials in your Instagram feed, in Stories, and on IGTV. Why Promote Customer Reviews and Testimonials on Instagram? With more than 1 billion […]

The post How to Use Instagram Customer Reviews for Maximum Impact appeared first on Social Media Marketing | Social Media Examiner.


by Val Razo via Social Media Marketing | Social Media Examiner

Google Launches Open Source 2FA Platform, OpenSK

Security is a big issue on the internet. When you have such a vast proverbial space where so much information is being spread around, it’s only inevitable that this information might just end up falling into the wrong hands. This is a big part of the reason why two factor authentication (2FA) has...

[ This is a content summary only. Visit our website https://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Zia Muhammad via Digital Information World

Template Review: Cardea

‘Cardea’ is a unique One Page Portfolio WordPress theme integrated with the powerful Elementor page builder. The theme featured 8 different layout options, each loading projects with AJAX – allowing the reader to browse your full portfolio without reloading the page. Other features include a sticky header navigation, smooth scroll to sections, marketing copy slider, about section with video overlay, blog feed, pricing table, skills graph, team, unique testimonial slider with alongside client logos and ends strong with an enquiry form.

If you don’t need content management, Cardea is also available as an HTML template.

Full Review


by Rob Hope @robhope via One Page Love