2

Can I determine the number of jQuery objects on a page?

I want to use the number of elements as a sort of weak benchmark for page complexity. I'm thinking that if I can reduce the number of elements that jQuery knows about , the page might run more efficiently.

Does this make sense?

Is it as simple as doing a * select and counting the results?


related:
How can I clear content without getting the dreaded “stop running this script?” dialog?

Community
  • 1
  • 1
Cheeso
  • 189,189
  • 101
  • 473
  • 713

3 Answers3

4

http://api.jquery.com/size/

var elementCount = $('*').size();

Although this might be more what you want:

var elementCount = $('body').find('*').size()
Eric
  • 95,302
  • 53
  • 242
  • 374
3
var n= 0;
for (var i in jQuery.cache)
    n++;

Now n holds the number of elements jQuery has ‘touched’ (added data to, such as event handlers).

Previously this used to be a whole lot, as it would ‘touch’ every element it was even checking for data. This unpleasantness is fixed in jQuery 1.4.

As for clearing content, yes, you can use innerHTML= '' to remove all the content without giving jQuery the chance to detach its data so very slowly. If you know there are no ‘touched’ elements inside the element that's a win, but otherwise it's a potential memory leak until the page is reloaded, as unused jQuery.cache data stays around.

Using live()/delegate() event binding avoids adding data to its target elements, which can allow you to use this short-cut more freely. However if you have a lot of events to bind and they're not selectors that are very easy to match quickly, this can make event handling slow.

(Because there is no browser-native speedup like querySelectorAll for matching elements against a particular selector as delegation needs to do; this is proposed for Selectors-API level 2.)

bobince
  • 528,062
  • 107
  • 651
  • 834
  • +1 - I was wondering about that. I knew jQuery added a serial number to elements, but didn't know where jQuery referenced them. – user113716 May 28 '10 at 14:22
0
var elementCount = $('*').length;

This doesn't really have much to do with jQuery except insofar as it's a handy way to get the answer.

Pointy
  • 405,095
  • 59
  • 585
  • 614