jQuery iterate through elements within another element

jquery each element
jquery each json
jquery find each
jquery each json array
jquery each break
jquery array of objects
jquery each li
w3c jquery each

I have HTML like this:

<div class="foo">
    <div class="bar1">A</div>
    <div class="bar2">B</div>
    <div class="bar3">C</div> 
</div>
<div class="foo">
    <div class="bar1">D</div>
    <div class="bar2">E</div>
    <div class="bar3">F</div> 
</div>
<div class="foo">
   ...etc.

I am trying to iterate through the "foo" divs to create objects like {bar1: A, bar2: B, bar3: C} with code sort of like this:

var arrayOfObjects= [];
var rows = $(".foo");

for (var i=0; i<rows.length; i++) {
    var row = rows[i];

    arrayOfObjects.push(
        { 
            bar1: row.find(".bar1").text(),
            bar2: row.find(".bar2").text(),
            bar3: row.find(".bar3").text()
        }
    );
}

I understand that this doesn't work because the original var rows = $(".foo"); creates an array of DOM elements, which don't have find() as a function. I also know that within the loop, I could start using elementByClass and innerHtml, but I feel like my brain starts crying whenever I start mixing jQuery-style and DOM-style selectors in the same code.

Is there a way to fix my code above so that I'm using jQuery selectors within the loop?

You can wrap your elements as jQuery objectslike this:

arrayOfObjects.push(
    { 
        bar1: $(row).find(".bar1").text(),
        bar2: $(row).find(".bar2").text(),
        bar3: $(row).find(".bar3").text()
    }
);

This makes you row a JQuery object, which has the 'find' method.

.each(), Description: Iterate over a jQuery object, executing a function for each matched that return a jQuery object also loop through the set of elements in the jQuery  In this post, I am going to show you how you can loop through DOM elements, arrays and objects using jQuery .each() function. The jQuery .each() function is an alternative to JavaScript for loop. The .each() function is not only efficient, but has many interesting properties, using which, you can easily and quickly iterate through elements

You can easily iterate through .row divs by using each(),

 var arrayOfObjects= [];   
 $(".foo").each(function(){
      var items = {"bar1" : $(this).find('.bar1').text(),"bar2" : $(this).find('.bar2').text(), "bar3" : $(this).find('.bar3').text()};    
      arrayOfObjects.push(items); //If you want to push all into an object and then into an array

      //or to use it on its own
      $(this).find('.bar1').text();
      $(this).find('.bar2').text();
      $(this).find('.bar3').text();
 });

Hope this helps.

Iterating over jQuery and non-jQuery Objects, It iterates over each matched element in the collection and performs a callback on that object. The index of the current element within the  The second parameter $('#mydiv') which is passed to the jQuery 'input' Selector is the context. In this case the each() clause will iterate through all input elements within the #mydiv container, even if they are not direct children of #mydiv.

             //find all the foo, and map them into new elements
var result = $('.foo').map(function(index, element){
  //we want to map all the children of the element into a single object
  return $(element).children().get().reduce(function(aggregate, childElement){
    //get the class off of the child and it's value, put them in the object
    aggregate[childElement.className] = childElement.innerText;
    
    return aggregate;
  }, {}); //second argument to the reduce() is the starting element
}).get(); //use get() to break the array out of the jQuery object

console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">
    <div class="bar1">A</div>
    <div class="bar2">B</div>
    <div class="bar3">C</div> 
</div>
<div class="foo">
    <div class="bar1">D</div>
    <div class="bar2">E</div>
    <div class="bar3">F</div> 
</div>

5 jQuery.each() Function Examples, jQuery's each() function is used to loop through each element of the target jQuery contains one or more DOM elements, and exposes all jQuery functions. Let's have another look at how an ordinary array can be handled: Another example of “each” with div element In this example, I am going to use a few div elements with same class names. The each jQuery method is attached to the link’s click event.

$(document).ready(() => {
  var arrayOfObjects = $('.foo').map(function() {
    return $(this).find('>*').map(function(obj) {
      return {
        class: $(this).attr('class'),
        text: $(this).text()
      };
    }).get().reduce( (obj, arr) => {
      obj[arr.class] = arr.text;
      return obj;
    }, {});
  }).get();
  
  console.log(arrayOfObjects);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">
    <div class="bar1">A</div>
    <div class="bar2">B</div>
    <div class="bar3">C</div> 
</div>
<div class="foo">
    <div class="bar1">D</div>
    <div class="bar2">E</div>
    <div class="bar3">F</div> 
</div>

How to use each() in jQuery, over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time. .each() is used directly on a jQuery collection. It iterates over each matched element in the collection and performs a callback on that object. The index of the current element within the collection is passed as an argument to the callback.

Something along these lines with .each would probably work

const $rows = $('.foo');
let arrayOfObjects = [];

$rows.each(function(i) {
  const $row = $(this);
  let obj = {};
  $row.children().each(function(ch) {
    obj = { ...obj, [this.className]: $(this).text() };
  });
  arrayOfObjects = [ ...arrayOfObjects, obj ];
});

console.log(arrayOfObjects);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">
    <div class="bar1">A</div>
    <div class="bar2">B</div>
    <div class="bar3">C</div> 
</div>
<div class="foo">
    <div class="bar1">D</div>
    <div class="bar2">E</div>
    <div class="bar3">F</div> 
</div>

jQuery.each(), functions. It's very useful for multi-element DOM manipulation, as well as iterating over arbitrary arrays and object properties. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.

.data(), been processed in alignment with the HTML dataset API. jQuery makes it really easy to loop through elements to get information, change state etc. There are already many useful functions for applying changes quickly to elements and being able to loop through elements as shown in this post adds another useful method for manipulating information in a web page with jQuery.

How to Loop Through Elements with the Same Class in jQuery, You can simply use the jQuery each() method to loop through elements with the same class The jQuery code in the following example will loop through each DIV elements and highlight <div class="box extraclass">Another Div box</div> The most basic concept of jQuery is to "select some elements and do something with them." jQuery supports most CSS3 selectors, as well as some non-standard selectors. For a complete selector reference, visit the Selectors documentation on api.jquery.com. link Selecting Elements by ID

Traversing DOM Elements using jQuery, jQuery Methods, Description. children(), Get all the child elements of the specified element(s). each(), Iterate over specified elements and execute specified call 

Comments
  • My jQuery is pretty rusty but I think you want .each