Last Updated: February 25, 2016
·
2.357K
· javisperez

Dont do $('#foo').get(0), use Plain JS instead

When using jQuery, some people might use it only for the selector. If that's your case, add an id attribute to your element and call it using getElementById method, is much much faster.

For example

If you have something like this:

<div id="foo">My Div</div>

Using jQuery, you can get that element by using $('#foo'), but if you need to use some of its natives properties (like value) you'll need to access the object itself, for this, you can use something like $('#foo').get(0) (which returns the first matched raw element), but that's a lot slower than doing:

document.getElementbyId('foo');

This is because when calling the jQuery selector, it will loop over the DOM Tree to match your selector.

Some people says "ok, but when using ID as selector let the browser to find that element", yes it does, but still has to loop all jQuery's own methods, properties and private functions, because after all, its a jQuery object.

2 Responses
Add your response

I completely concur; jQuery's ease of use is both it's greatest blessing and it's greatest weakness because everything is so simple these days that developers often forget that there may be a quicker/more efficient way of achieving the same result with native JS.

over 1 year ago ·

That's exactly the point, some times, its just too comfortable to use jQuery's methods, with all its internal loops and everything that cost performance.

over 1 year ago ·