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?
HTML. After seeing the result of the above code, it is crystal clear that the ID selector is the fastest.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With