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.removeSpecialChars().toUpperCase() + "").size() != 0) {
var row = $("#" + machineId + packageId.removeSpecialChars().toUpperCase() + "");
}
wouldn't this execute packageId.removeSpecialChars().toUpperCase()
twice?
OR would this be better option?
var row = $("#" + machineId + packageId.removeSpecialChars().toUpperCase() + "");
if (row)
{
// do something
}
However, wouldn't it throw an exception when not found?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With