简体   繁体   中英

Do you need to check if a jQuery object exists?

Let's say you have a website of 100 pages and there is a div with an id of #unique-div that only appears in page-5.html, but not in the other 99 pages and to be extra simple with the example you have a JS file that is loaded on all pages, and inside it there is this:

var uniqueDiv = $('#unique-div');

uniqueDiv.addClass('random-class');

does that have any negative impact in any possible way (for instance, performance)? Would it better to do a length check first?

var uniqueDiv = $('#unique-div');
if ( uniqueDiv.length ) {
    uniqueDiv.addClass('random-class');
}

If so, why?

Or what about if you are chaining objects like this:

var uniqueDiv = $('#unique-div');

someVar.add(moreVars).add(uniqueDiv).addClass('random-class');

If the object doesn't exist, what happens?

I tried looking this up, but I have always wondered this.

It is the responsibility of ANY jQuery method to have a "proper" behavior whether there are 0, 1 or more than 1 DOM objects in the current jQuery object that they are called on. So, as long as you aren't using some broken jQuery plug-in methods, you do not have to test the length before calling a method and this includes situations where you are using chaining.

So, in your case this would be perfectly fine, even if you had no idea whether #unique-div actually existed:

$('#unique-div').addClass('random-class');

If the div didn't exist, then the .addClass() method would just do nothing.

Note: that some methods that retrieve a value such as .val() are coded to only operate on the first DOM element in a jQuery object and you will have to check with an individual method like that what they are coded to return if there are no DOM objects in the jQuery object. For example, .val() will return undefined when there are no DOM objects in the jQuery object.

There might be some infinitesimal amount of performance saving, but it's really negligible. There are probably going to be plenty of times in your code you'll do a for-loop through an array, acknowledging the length might be zero.

JQuery objects always have some size to them, and all methods I know of (ie, addClass) are equipped for empty sets, so I don't see any issue with skipping the length check.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM