Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.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?

like image 684
ShaneKm Avatar asked Mar 05 '13 11:03

ShaneKm


1 Answers

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
}
like image 59
Anthony Grist Avatar answered Oct 12 '22 17:10

Anthony Grist