Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery context selector vs .find()

What is more efficient?

var container = $("#container");

// 1
var links1 = container.find("a");

// 2
var links2 = $("a", container);

I personally prefer $("a", container) because it looks better, but are they different in performance?

like image 731
Catalin Avatar asked Aug 14 '13 07:08

Catalin


People also ask

Which jQuery selector is fastest?

HTML. After seeing the result of the above code, it is crystal clear that the ID selector is the fastest.

Why we use find in jQuery?

find() method allows us to search through the descendants of these elements in the DOM tree and construct a new jQuery object from the matching elements. The . find() and . children() methods are similar, except that the latter only travels a single level down the DOM tree.

What is context in jQuery selector?

The context property contains the original context passed to jQuery, which could be a DOM node context, or, if no node is passed, the document context.

What does $() mean in jQuery?

In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery. A (selector) to "query (or find)" HTML elements.


1 Answers

The context selector $("a", container) is converted to find. find() will be faster but in most cases this could be ignored. I would go for find() as its syntax is quite stright forward for me. This post has performance comparison that would help you deciding which one you would use.

like image 84
Adil Avatar answered Nov 08 '22 02:11

Adil