Let’s say I had the following HTML and Javascript. Here, there is only 1 div on the page, but at any given time, there could be a total of 2 divs (dynamically inserted).
In jQuery, should you first test to see if an element exists before doing anything to it, especially if you know there’s a chance it might not be present?
Should I test it with if (('#div2).length > 0)?
Or should I just let jQuery figure it out? I know if doesn’t exist, jQuery is smart enough to know the element isn’t there, so it won’t do anything to it nor would it throw an error. But is it better to first test to see if it exist? Best practice maybe or is there a performance difference?
HTML:
<div id="div1"></div>
Javascript:
$('#div1').text('Hello World!');
/*
Should I first test and see if this div exists?
With if (('#div2').length > 0)
Or leave it as is and let jQuery handle it
*/
$('#div2').text('Should I have first tested to see if this div existed?');
The object returned by jQuery’s factory function is array-like. The selected DOM elements will be set to numeric indices (
{0: elem1, 1:elem2, etc}). The length property will be set to the number of matched elements.jQuery’s methods are all designed to iterate over the collection of elements to perform an action. This essentially means that
obj.test('foo')is equivalent to:If there are no elements in the collection, the methods don’t perform any action, because the iterator never iterates.
So, tl;dr, there’s rarely ever a reason to check if the selection contains elements before performing actions on the selection.