Jquery each function with example

Jquery each function example

Jquery each function

The Jquery each function or method is used to make DOM looping constructs concise and less error-prone.


$(selector).each()

Syntax:

$('selector').each(function(){
  // your code
});

Jquery each function example

<!DOCTYPE html>
<html>
<head>
<title>Jquery each function example</title>
<script src="https://code.jquery.com/jquery-3.4.0.js"></script>
</head>
<body>  
  <p class="line">First line</p>
  <p class="line">Second line</p>
  <p class="line">Third line</p>
  <p>Fourth line</p>
  <p>Fifth line</p>  
<script>
$(function(){
  $('.line').each(function(){
    console.log($(this).text());
  });
});
</script>
</body>
</html>

$.each()

The $.each() function is not the same as $(selector).each().

This is a generic iterator function, which can be used to seamlessly iterate over both objects and arrays.

Example with an array:

$(function(){
  var _array = ['Leanne Graham','Ervin Howell','Clementine Bauch'];
  $.each(_array, function( index, value ) {
    alert( index + ": " + value );
  });
});

Example with an object:

$(function(){
  var _object = {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "[email protected]"
  }
  $.each(_object, function( index, value ) {
    alert( index + ": " + value );
  });
});

A simple application –

In this application, I am trying to give you an idea of ​​how to use the $.each() function.

<!DOCTYPE html>
<html>
<head>
<title>Jquery</title>
<script src="https://code.jquery.com/jquery-3.4.0.js"></script>
<style>
  .posts {
    max-width: 900px;
    margin: 0 auto;
    font-family: sans-serif;
  }

  h1 {
    text-align: center;
    margin-bottom: 0;
  }

  .posts div {
    border-bottom: 1px dashed #333333;
    padding: 30px;
  }
</style>
</head>
<body>
<div class="posts">
  <h1>All posts</h1>
</div>
<script>
$(function() {
    
  $.ajax({
    url: "https://jsonplaceholder.typicode.com/posts",
    method: "GET",
    success: function(data) {
      var _container = $('.posts');
      var _allPosts = [];
      var _posts = data;

      $.each(_posts, function(i, post) {
        var single_post = $('<div/>', {
          html: '<h3>' + post.title + '</h3><p>' + post.body + '</p>'
        });
        _allPosts.push(single_post);
      });
      _container.append(_allPosts);
    }
  });

});
</script>
</body>
</html>

Read also:

Posts Navigation


Leave a Reply

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