forEach()

Iterate When You Really Need To

With SniperJs, you’ll rarely need to manually loop through elements just to apply actions.

Most DOM operations are already handled gracefully and intelligently.


Syntax

$(selector*).forEach(callback);

⚠️ Note: .forEach() works only when the selector targets multiple elements (*).


Callback Signature

(element, index, list) => {}
  • element → current DOM element

  • index → zero-based position

  • elementList - The selected Lists of elements either NodeList or HTMLCollection


Basic Example

$('.card*').forEach((el, i) => {
  el.dataset.index = i;
});

Conditional Logic Example


When Should You Use .forEach()?

Use .forEach() only when you need to do something beyond a direct action, such as:

  • Conditional logic per element

  • Reading values

  • Custom computations

  • Advanced DOM interaction

That’s where .forEach() comes in.

Key Takeaway

SniperJs minimizes the need for loops. If all you want is to apply an action — just use the API directly. If you truly need to iterate — .forEach() is there.

Last updated