DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • jQuery vs. Angular: Common Differences You Must Know
  • CSS3 Transitions vs. jQuery Animate: Performance
  • Better Scaffolding with jQuery - Part I
  • How to Call Rest API by Using jQuery AJAX in Spring Boot? [Video]

Trending

  • Teradata Performance and Skew Prevention Tips
  • Microsoft Azure Synapse Analytics: Scaling Hurdles and Limitations
  • Solid Testing Strategies for Salesforce Releases
  • The Role of Retrieval Augmented Generation (RAG) in Development of AI-Infused Enterprise Applications
  1. DZone
  2. Coding
  3. Frameworks
  4. Using the jQuery .each() Function (with Examples)

Using the jQuery .each() Function (with Examples)

With jQuery dominating JavaScript development, this article is a deep dive into one of the main functions in the library— each().

By 
Paul Underwood user avatar
Paul Underwood
·
Feb. 26, 16 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
98.7K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, we're going to look into the usage of the jQuery each() function which will allow us to loop through different datasets such as arrays or objects. jQuery each is one of the most used functions in jQuery so I think it's important to understand what you can do with it.

The jQuery each function is used to loop through data the easiest way to think of it is that it's similar to a foreach loop in other languages. So, you can use it to loop through a number of DOM objects from the same selectors. For example, if you want to add a target="_blank" to all links on the page then you will select all links and loop through each of them to add a target="_blank".

$('a').each(function(i){
    $(this).attr('target', '_blank');
});

Let's investigate how this works. First, we get all the anchor links on the page by using the following selector.

// Get all anchor links
$('a')

Next, we use the each function to loop through all the links.

$('a').each(function(i){
    // Performs tasks to each of the links
});

When you're inside the each function you can access the current element it is loop through by using the this keyword, but this object will not be a jQuery object and therefore if it's a DOM element you will not be able to use any jQuery functions on it. The solution to this problem is to wrap the this inside a jQuery object definer.

$('a').each(function(i){
    // Performs tasks to each of the links
    $(this);
});

When we have the current looped element inside a jQuery object we can then add a new attribute to the link by using the attr function.

$('a').each(function(i){
    $(this).attr('target', '_blank');
});

Get the Current Index of the Loop

In the above example, you'll notice the i inside the function() parameters. This variable is populated with the current index of the each to see this working have 10 links on the page.

<a>Link 1</a>
<a>Link 2</a>
<a>Link 3</a>
<a>Link 4</a>
<a>Link 5</a>
<a>Link 6</a>
<a>Link 7</a>
<a>Link 8</a>
<a>Link 9</a>
<a>Link 10</a>

Then output the current index by alerting this to the user.

$('a').each(function(i){
    alert(i);
});

Loop Through Arrays

In the above example, you saw how you can select DOM elements and loop through them but you can also use it to loop through arrays of data and get both the index and the value of the position inside the array.

var fruit = ['orange', 'apple', 'banana', 'grapes', 'kiwi'];

$.each(fruit, function(index, value){
  console.log(index + ' ' + value);
});

In the console, it will output the following.

"0 orange""1 apple""2 banana""3 grapes""4 kiwi"

Loop Through Objects

What if you're using objects to store data and not arrays, the each function will take care of that the same way as you can see in the following code.

var fruitObj = {
   1: 'orange',
   2: 'apple',
   3: 'banana',
   4: 'grapes',
   5: 'kiwi'
};

$.each(fruitObj, function(key, value){
  console.log(key + ' ' + value);
});

The output of looping through the object is below.

"1 orange""2 apple""3 banana""4 grapes""5 kiwi"

JQuery

Published at DZone with permission of Paul Underwood, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • jQuery vs. Angular: Common Differences You Must Know
  • CSS3 Transitions vs. jQuery Animate: Performance
  • Better Scaffolding with jQuery - Part I
  • How to Call Rest API by Using jQuery AJAX in Spring Boot? [Video]

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!