Filter and Each

Narrow a set with filter(), and loop over it with each().

Syntax$(selector).each(function (index, element) { ... });

.filter(selector) keeps only the elements in a set that match a condition. .each() runs a function once per element.

$("li").each(function (index) {
  $(this).text((index + 1) + ". " + $(this).text());
});

Inside .each(), this is the current DOM element and index is its position.

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A search box uses .filter() to show only list items whose text contains the search term typed by the user.
  • A report generator uses .each() to loop over table rows and build a CSV string from each row's cell values.
  • A form serializer uses .each() over all :input elements to collect their names and values into a custom object.

More examples

Filter list items by search text

.filter(function) hides all items then shows only those whose text passes the predicate test.

Example · html
<input id="search" placeholder="Search..." />
<ul id="items">
  <li>Apple</li><li>Banana</li><li>Cherry</li><li>Blueberry</li>
</ul>
<script>
$(function () {
  $("#search").on("input", function () {
    var q = $(this).val().toLowerCase();
    $("#items li").hide().filter(function () {
      return $(this).text().toLowerCase().includes(q);
    }).show();
  });
});
</script>

Loop over items with .each()

.each() iterates every matched element; index and el give the position and DOM node for each iteration.

Example · html
<ul id="prices">
  <li data-price="10">Widget A</li>
  <li data-price="25">Widget B</li>
  <li data-price="5">Widget C</li>
</ul>
<p>Total: $<span id="total">0</span></p>
<script>
$(function () {
  var sum = 0;
  $("#prices li").each(function (index, el) {
    sum += parseInt($(el).data("price"), 10);
  });
  $("#total").text(sum);
});
</script>

Collect form data with .each()

.each() over :input elements builds a plain object keyed by field name, useful before an AJAX submission.

Example · html
<form id="survey">
  <input name="name" value="Alice" />
  <input name="city" value="Paris" />
</form>
<pre id="output"></pre>
<button id="collect">Collect</button>
<script>
$(function () {
  $("#collect").click(function () {
    var data = {};
    $("#survey :input").each(function () {
      data[this.name] = $(this).val();
    });
    $("#output").text(JSON.stringify(data, null, 2));
  });
});
</script>

Discussion

  • Be the first to comment on this lesson.
Filter and Each — jQuery | SoundsCode