Efficient Selectors
jQuery selectors differ in speed. ID selectors are fastest; complex CSS selectors are slowest. Use context to narrow the search scope.
jQuery selectors differ in speed. ID selectors are fastest; complex CSS selectors are slowest. Use context to narrow the search scope.
// Fastest: getElementById internally
$("#main");
// Good: tagName + class
$("div.card");
// Slow: attribute selector on all elements
$("[data-id=5]"); // scans all elements
$(".card[data-id=5]"); // scoped to .card — much faster
// Use context to limit scope
$("input", "#form"); // inputs within #form only
$("#form").find("input"); // equivalent, explicitly chained
// Avoid universal selectors
$("*"); // extremely slow!
$(".container *"); // still slow
Provide context ($("#parent").find()) to limit the traversal to a subtree of the DOM.