javascript - Do you need to check if a jQuery object exists? -


Assume that you have a 100 pages website and it has only one div with a unique div id page-5 . Html, but not in 99 pages, and for example to be extra simple, you have a JS file that loads on all pages, and inside it is:

  Var uniqueDiv = $ ('# Unique-div'); UniqueDiv.addClass ('Random Level');  

Is there any negative effect in any possible way (for example, performance)? Would it be better to check the length of the first?

  var uniqueDiv = $ ('# unique-div'); If (uniquediv. Lamp) {uniqueDiv.addClass ('random-class'); }  

If so, why?

Or if you are sticking to such things:

  var uniqueDiv = $ ('# unique-div'); SomeVar.add (moreVars) .add (uniqueDiv) .addClass ('random level');  

What happens if the object is not present?

I tried to see it, but I have always thought this.

This is the responsibility of any jQuery method to "proper" behavior whether 0, 1 or more The more 1 dome objects are the current jQuery objects that they say, so long as you are not using some broken jQuery plug-in methods, you do not have to check the length before calling a method and It involves situations where you are using chaining.

So, in your case it will be absolutely right, even if you do not know that # unique-div actually exists:

 < Code> $ ('# unique-div'). AddClass ('Random Level');  

If the div was not in existence, then the .addClass () method would not do anything.

Note: Some methods that retrieve values ​​such as .val () , only work on the first dome element in a jQuery object, For example, if there are no DOM objects in the JQuery object, they will be tested as if they are coded back. For example, .val () will be undefined The DOM object is not in the object.


Comments

Popular posts from this blog

import - Python ImportError: No module named wmi -

Editing Python Class in Shell and SQLAlchemy -

c# - MySQL Parameterized Select Query joining tables issue -