Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way to access DOM elements in jQuery?

I am writing a jQuery plugin and I am at the optimization stage.

I wonder which of these leads to a quicker script in general, and what sort of mitigating factors are important:

  1. Have the script generate lots of classes and ids at the start so finding elements in the dom is easier (quicker too?) later on.
  2. Keep classes and ids to a minimum (so save time by not creating them), but then look for elements in more convoluted ways later (eg the nth item in an object), which I presume is slower than getting by id/class.
like image 404
wheresrhys Avatar asked Nov 28 '22 08:11

wheresrhys


1 Answers

The way the browser works is that upon load it creates an in-memory DOM tree which looks as follows:

                                              P
                               _______________|______________
                              |                              |
                          childNodes                    attributes
                ______________|___________                   |
               |              |           |            title = 'Test paragraph'
         'Sample of text '   DIV   'in your document'
                              |
                          childNodes
                    __________|_______
                   |          |       |
           'HTML you might'   B     'have'

So when you lookup P > DIV > B, the lookup has to find all P elements, then find all DIV elements within P and then find all B elements within DIV. The deeper the nesting the more lookups it needs to do. Further, it might find all P > DIV only to find that none of them have B and it will have wasted time looking through all P > DIV matches.

Lookups by ID are faster because IDs are guaranteed to be unique so the DOM can store them as hash table entries which have very fast lookups. In terms of jQuery the implementation might be slightly different, however, document.getElementById has the fastest lookup time so $('#my_node_id') should also be quite fast.

Consequently, if your node doesn't have an ID, you can find the nearest ancestor that does and find your node relative to that ancestor

#my_node_id > div > b

because the look up only needs to happen under the sub-tree of #my_node_id it will be faster than p > div > b

like image 125
aleemb Avatar answered May 03 '23 18:05

aleemb