Skip to content Skip to sidebar Skip to footer

Javascript Check If Dom Element Exists Best Practice

What is the best practice to check if a DOM element exists in javascript? Should one check if an item exists prior to using it, like so? if ($('#' + machineId + packageId.removeSpe

Solution 1:

When you're actually working with DOM elements, then yes, you should check that it exists before you attempt to work with it to avoid JavaScript errors. However, you're not working with DOM elements, you're working with a jQuery object that (potentially) contains DOM elements.

jQuery functions already handle cases where there are no matches in its set of elements, so you don't need to explicitly check for yourself that there are elements before attempting to work with them. You'd only need to do so if you're trying to directly reference DOM elements from inside that set, using the .get() function or the [index] square bracket notation.

As an aside, the .size() jQuery function was deprecated in version 1.8, you should use the jQuery object's length property directly to check if there are elements, so:

var $object = $('a-selector');
if($object.length) {
    // there's at least one matching element
}

Solution 2:

Better to cache it:

var machId = $("#" + machineId + packageId.removeSpecialChars().toUpperCase());
if (machId.size() != 0) {
   var row = machId;
}

Solution 3:

General programming conventions say don't repeat yourself. So, in this case, you could at least do the finding of the thing only once and keep a variable reference:

var thing = $("#" + machineId + packageId.removeSpecialChars().toUpperCase() + "");

Then the selection lookup doesn't happen twice, redundant method calls removed etc. This also has the benefit of allowing you to write more self-explanatory code, when you can name a variable to something meaningful, other than thing, or, eeek!, a (though it isn't necessarily so that code must be more meaningful, people still use names like a!)

if(thing!=null) { }
if(thing.size()!=0) {

} 
etc.

As for calling methods multiple times, that's often unavoidable.

Solution 4:

It does, what you need is:

var a = $("#" + machineId + packageId.removeSpecialChars().toUpperCase() + "");
if (a.size()) {
    var row = a;
}

Solution 5:

You basically need to see if the DOM element is exist in your HTML, but beer in mind that jQuery doesn't throw a fatal error if the element not exist in your DOM, but would a good practice to check, it adds one more secure layer on your code, there was something called .size() that deprecated from version 1.8, so not recommended to use even you use old version of jQuery, so the best solution at the moment would be something like below code:

if($('.class').length) { // check if any element with this class exist, if not exist, it return 0 and can not pass the if estatement// do something
}

Post a Comment for "Javascript Check If Dom Element Exists Best Practice"