New in jQuery 3 is the ability to iterate over jQuery objects using a for...of
loop. This by itself isn't a big deal. For one thing, it's rare that we need to explicitly iterate over jQuery objects, especially when the same result is possible by using implicit iteration in jQuery functions. But sometimes, explicit iteration can't be avoided. For example, imaging you need to reduce an array of elements (a jQuery object) to an array of string values. The each()
function is a tool of choice here:
const eachText = []; $('td') .each((i, td) => { if (td.textContent.startsWith('H')) { eachText.push(td.textContent); } }); console.log('each', eachText); // ["Hamlet", "Henry IV, Part I", "History", "Henry V", "History"]
Listing 2.17
We start off with an array of <td>
elements, the result of our $('td')
selector. We then reduce it to an array of strings by passing the each()
function a callback that pushes each string that starts with "H" onto...