How does jQuery handle elements that do not exist on the page?

I have a theory question about what happens when you have jQuery to search for elements / snap to elements that do not exist on the page.

For example, I have a javascript file that contains many Click events, however on some pages these click events are not used. Instead of creating multiple javascript files and having duplicate code, I reduced most of my code to a single file.

$('#target').click(function() { alert('Handler for .click() called.'); }); 

Basically, to bring my paragraph to a few simple sentences. What happens when id "target" does not exist? How does jquery handle such a case?

Now that I am working on my website, it seems that FireFox's memory usage is growing like crazy. Not sure if it’s just FireFox or not, but if I don’t have an element on the page, it causes a memory leak by binding to elements that do not exist?

Just curious what happens behind the scenes.

Thanks!

+6
source share
5 answers

If no elements match your selector, you will get an empty jQuery object (one that contains no elements).
Calling any method other than live() on an empty jQuery object will do nothing and will not waste resources.

+5
source

jQuery always works on item lists. When the selector does not match anything, you get an empty list and manipulate that does nothing.

Attaching events to non-existent elements, as a matter of fact, does nothing, so no, this is not a memory leak.

+2
source

the $ () function will cycle through the elements in the window. If #target is found, an onclick event will be added.

If this does not exist, nothing will happen, you will get an empty jQuery object

+2
source

The result of an element that is not present should be that it is simply not connected with anything and, therefore, clicking on the fact that it is not there will not affect it.

I would also like to note that if an element is added via ajax and you have attached the '#target' element to a specific click function, as in the published code, it will not function before calling ajax, In these cases you should use the ".live "to ensure that the function is bound to the element. In addition, Firefox is a memory robot, and is often used to quickly use memory.

0
source

As I understand it, the $ ('# target') selector will not select anything, so the click will not be bound to any elements. This will not cause any memory problems or anything else.

-1
source

Source: https://habr.com/ru/post/908471/


All Articles