5 jQuery.each() Function Examples

3D ad banner ad revenue ad revenues adobe XD Advanced advanced-css-tools advanced-css-tutorials AdvancedCSS AdvancedCSS-hub agency Agile Agile Development ai Ajax Alex Skill Kit Alexa Alexa skill AlexW Amazon Alexa amazon developer analytics Angelap angular AngularJS Animation anime.js ANN api apollo Appsflyer array methods artificial neural network Async async components AurelioD automation Avocode AWS AWS Lambda axios b2b b2c baas background background eraser tool Banner banner ad Bannersnack bawmedia bem bitcoin black friday Blogs bootstrap bot browser testing Browsers build process bundler Business business success C Canvas & SVG career Career Advancement CDN Chakra UI charting chat app chatbots ChatKit chrome chrome developer tools chrome extension chrome extensions chromium ciphering cli cli tools climate climate action clojure Cloud cloud hosting CloudFlare Cloudways cms CNN code challenge ColinI collaboration collaboration tools compiler components const assertions constructs content content delivery network context api convoluted neural network create react app cron job cross browser testing cross platform development cross-browser cryptocurrencies cryptocurrency CSS CSS Architecture css blur css challenge css framework css frameworks css grid css modules CSS print css rem css typography CSS-in-JS CSS3 css3 transforms cssbattle.dev D3.js data science data visualization database databases debugging decoupled cms deep linking delay Design Design & UX design career design handoff Detox dev environment developer tools DevOps devtools diagnostic analytics digit recognition digital agency digitalocean Discord discounts django Docker Docker Containers E-commerce ECMAScript edge computing editor elastic em units employment encryption end-to-end testing energy energy usage Entrepreneur Entrepreneurship environment erasing backgrounds es6 ES6 classes eslint Expo Express FaaS face detection face recognition fast wordpress themes Feathers Feathers.js figma flask flatfile flexible wordpress theme framework Frameworks freelancing functional programming functions gatsby generators geolocation gitCS github github API Google Photos GraphCMS graphing graphql Growth Grunt grunt-watch Gulp haskell headless CMS hooks hosting HTML HTML & CSS html preprocessor HTML5 HTML5 Dev Center https://www.sitepoint.com/windows-linux-subsystem-2-windows-terminal IAAS IDE Illustration image optimization immutability Interview ionic IP2Location jade jamesh JavaScript javascript framework javascript frameworks javascript tooling Jest job job interview joelf jQuery jQuery functions jquery get url params jquery string functions jQuery.each() jQuery.each() Array Example jquery4u js js framework JS tooling Keras keycdn kubernetes lambdatest launch checklist Layout learn-advanced-css learn-modernjs Learn-Node-JS learn-vue Let's Encrypt Lift linux linux containers location tracking LouisL machine learning Managed managed hosting mariap marvel MATLAB MBaaS mekanism mind map mind mapping mindmapping Mobile mobile attribution Mobile Design modernjs modernjs-hub modernjs-tools modules monday mongodb MTCNN multi-threading mysql MySQL install natural language processing Navigation navigation library nest Next.js nilsonj node node version manager node-hub Node-JS-Tools Node-JS-Tutorials node-mysql module Node.js nodejs noops npm nvm objects octobercms Offers on-premise online publishing PaaS Package Management package manager pair programming pairing pause Percy Performance Photography & Imagery Photoshop Photoshop Tutorials & Articles pip pipeline portfolio portfolio builders preprocessors prettier print styles Prisma Private Class Fields product design Profitability Programming PubNub Pug Puppeteer Pusher python python framework python interview python job Quasar query strings quick-tip quote builders r Raw JavaScript React react components React Hooks React Hooks Form React native reactive Reactive Programming reactive web apps read offline Reat native elements Recurring Payments recursive types RedBox redux rem units remote work remote work tips removing backgrounds resilient Resources responsive REST restful api Review SaaS sampling sass Scss self sencha serverless serverless computing shared hosting sharing state sharpen side project siteground sketch slashdata sleep Software sorting specifications speech recognition speech recognition api sponsored ssl state state management static module bundler StudioWorks Styled Components styling React components survey sustainability svelte sympli Tailwind task runner telegram bots Template engine Testing text to speech Themes Tic Tac Toe Tinder toggle Tolerance tooling tooling anxiety tools Tools & Libraries transformations TypeScript Ubuntu UI UI Design Usability user experience user research UX ux issues vanilla javascript VGGFace2 virtual machine visual testing voice recognition vps vue Vue CLI vue dev environment vue-hub vue-tutorials vue.js vuetify vuex wait WatermelonDB Web Web Design web hosting Web Hosting & Domains Web standards web workers webpack website builders website performance WebSockets windows windows 10 home Windows Subsystem for Linux Windows Terminal wix women women in tech WordPress wordpress themes WordPress theming work workers workflow working remotely workplaces WPEngine WSL WSL2 YellowBox Zeplin

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.

Original Article

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.