Selectors Performance
In this page:
Prefer IDs
Because ids are unique, jQuery can hand an ID selector straight to the browser's native getElementById, making it the fastest lookup available. Class and attribute selectors, by contrast, require jQuery to do more work internally to find every match.
Example: Prefer IDs
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="main">Content</div>
<script>
console.log($("#main").length);
</script>
</body>
</html>
Use Specific Selectors
A more specific selector, like '#list li.active' instead of just '.active', gives the browser fewer candidate elements to check, which noticeably speeds up selection on large pages.
Example: Use Specific Selectors
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<ul id="list"><li class="active">A</li><li>B</li></ul>
<script>
console.log($("#list li.active").length);
</script>
</body>
</html>
Cache Repeated Selections
Storing the result of a selector in a variable -- var $rows = $('.row') -- means jQuery only searches the DOM once, instead of re-running the same query every time you need those elements again.
Example: Cache Repeated Selections
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div class="row">A</div><div class="row">B</div>
<script>
var $rows = $(".row");
console.log($rows.length);
$rows.css("color", "blue");
</script>
</body>
</html>
Use find for Descendants
Calling .find() on an already-selected parent restricts the search to that parent's descendants only, which is faster than re-querying the whole document with a broader selector. This pattern avoids re-scanning the entire document when you already know which container the elements you want live inside.
Example: Use find for Descendants
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="parent"><p>Inside</p></div>
<script>
var $parent = $("#parent");
console.log($parent.find("p").length);
</script>
</body>
</html>
Avoid Unneeded Work
Selecting exactly what you need, and reusing that cached selection for every follow-up operation, avoids redundant DOM traversal -- the single biggest performance win in jQuery-heavy code.
Example: Avoid Unneeded Work
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div class="box">A</div><div class="box">B</div>
<script>
var $boxes = $(".box");
$boxes.addClass("ready");
$boxes.css("border", "1px solid black");
</script>
</body>
</html>
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: