Caching Selectors
Cache jQuery objects in variables to avoid repeated DOM queries. Prefix cached variables with $ for clarity.
Cache jQuery objects in variables to avoid repeated DOM queries. Prefix cached variables with $ for clarity.
// BAD: DOM queried 4 times for same element
$("#nav").addClass("active");
$("#nav").css("top", "0");
$("#nav").show();
$("#nav").find("a").first().focus();
// GOOD: cached
const $nav = $("#nav");
$nav.addClass("active").css("top", "0").show().find("a").first().focus();
// Cache selectors used in loops
const $items = $(".item");
$items.each(function() { $(this).text($(this).data("value")); }); // still re-wraps
$items.each(function(i, el) { el.textContent = el.dataset.value; }); // avoid wrapper
Inside .each(), use el.textContent instead of $(this).text() for tight loops — avoids jQuery object creation.