4 ms·
Interacting with the DOM is what's slow. It's especially slow if the native querySelectorAll method isn't available because any non-trivial selections necessita
by xtian 16y ago
Interacting with the DOM is what's slow. It's especially slow if the native querySelectorAll method isn't available because any non-trivial selections necessitate iterating over the DOM tree. That's why you don't want to re-query a selection multiple times.
That's also why it's recommended that all selections start with an id. The size of the tree to iterate over can be quickly reduced using the native getElementByID method.
In the case of $(this), the DOM node is already passed to the event handler, so wrapping it in a jQuery object doesn't touch the DOM tree at all. Furthermore, I always cache it (var $this = $(this);) if I'm going to use it more than once.
Also, in your first example, you don't have to rewrap containers[index] in a jQuery object. All the elements in the selection are already wrapped.
- emehrkay 16y ago> Also, in your first example, you don't have to rewrap containers[index] in a jQuery object. All the elements in the selection are already wrapped. Really? I think that is the whole point of this long comment thread -- that the elements in a collection arent already wrapped. http://jsfiddle.net/8nqtA/ http://jsfiddle.net/8nqtA/ This doesnt work unless i wrap a[i] in $() But like you're saying, it may be fruitless since the dom is the bottleneck and we're bypassing it by already having the element.
- M1573RMU74710N 16y agoWell there's a few problems with that example: 1) You've got a "global" named a and then a local variable (via the argument) inside the each function called "a"...so that really confuses things. 2) a[i] where a is a jQuery object returns an unwrapped DOM element...what you want is .index(). 3) What you're doing is sort of roundabout... Why not: var d = $('div'), a = $('a'); a.each(function(i, el){ d.text(d.text() +' '+ $(this).text() ); }); Or if you really want to do it your way: var d = $('div'), a = $('a'); a.each(function(i, el){ d.text(d.text() +' '+ a.index(i).text() ); });
- arethuza 16y agoShouldn't the second one be: var d = $('div'), a = $('a'); a.each(function(i, el){ d.text(d.text() +' '+ a.eq(i).text() ); }); Using eq(i) rather than index(i)?
- emehrkay 16y agoI feel like this should have been the first replay to my rant. The nodes are already wrapped in the jQuery object, just need to use eq to access them by index. I've never seen that before, thanks
- xtian 16y agoAh yeah, I forgot you had to use .eq().
- ahrjay 16y agoThe selector engine runs right to left so even if you start with an id but end it with an element it will still be an expensive query. I think the key is to think about your selectors and not go overboard because it's easy.