Question

I mostly call jQuery elements by the id of the DOM object using the $('#id') syntax. I think that this goes through the selector algorithm, and spends some time on that process.

I was wondering if there is a way to dig into that function and access jQuery objects from the id of the DOM in a more direct way (at the lower level) to improve performance. Will it worth doing so? If so, how can I do it?

Était-ce utile?

La solution 3

Going native will always be faster / more direct:

var id = document.getElementById("id");

But you will loose the benefits of wrapping your object in a jQuery wrapper.

You can also do :

$(document.getElementById("id"))

That way you are passing in the direct object rather than performing a lookup on the dom.

Autres conseils

If you want to improve performance, keep a jQuery object that's used for single node synchronous operations

var _id = $(document);

Then update its 0 property when you need to fetch by ID.

_id[0] = document.getElementById("id");

_id.css(...);

This eliminates the vast majority of its overhead. Because JS is single threaded, you can reuse this object wherever needed. But if you want to do some operation in a setTimeout(), you should probably just create a new object to be safe.

When you pass jQuery a single, lone ID selector, it automatically skips any selector processing and calls document.getElementById() directly. It's only when the selector string consists of anything more than an ID selector that it always treats it like a selector (this includes selectors like div#id, .class#id, or even #wrapper #id).

In most cases, this is something you don't have to worry about, since jQuery already does a lot of optimization for you. But if you're paranoid and want to remove every hair and every ounce of any possible overhead, see cookie monster's answer.

You want to use getElementById like this

var name = document.getElementById('id');

Actually.... this will depend on the browser u will be using to run the script.... here i did some dig on the internet..... i found a test result on this topic.....

Here is the Site

As to them JQuery selectors are faster than the native JS code.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top