Best Practices and Pitfalls

Harry · 11 Sep 2026 · 8 views

Patterns That Keep jQuery Clean

  • Cache selections: var $list = $('#list'); - do not re-query the DOM in loops.
  • Start on ready: wrap setup in $(function () { ... });.
  • Delegate dynamically: use .on('click', 'li', fn) for rows added later.
  • Target with IDs near hot paths: IDs are the fastest selector.
  • Chain deliberately: chains read well, but one long chain hides errors; split when it hurts clarity.

Pitfalls to Avoid

  • Reading values in a loop too often: cache var v = $el.val().
  • Binding inside a loop: binds handlers repeatedly - attach once and delegate.
  • Forgetting e.preventDefault(): form submits or link jumps happen when you did not stop them.
  • Multiple elements, single value: .text() on several elements reads only the first; use .each() to collect all.
  • Assuming elements exist: a bad selector returns an empty set silently - check .length.

Performance Habit

var $cards = $('.card');           // query once
$cards.addClass('ready');           // operate on the cached set
var firstText = $cards.first().text();

Key Points

  • Cache selections and delegate events for speed and correctness.
  • Prevent default behaviour consciously.
  • Check .length to catch empty selections.
  • Keep handlers out of loops; keep chains readable.
Share this post:

Comments (0)

Please login or register to comment.