Should we check if element exists before assigning events?

coffeescript, javascript, jquery-events

Solution

Every method call in jQuery is wrapped in a `.each` function, so checking if an element exists is usually not necessary - there will be no iterations of the called function if the set is empty, it fails silently. The example given is a good example of that, there's no harm or performance penalty in just calling `$('#progressbar').progressbar()` directly.

When you do want to do that, probably because you're manipulating the DOM or doing some expensive operation depending on the presence of an element, make sure you cache the call, specially if it's a complex selector:

specialThings = $('section .special')

if specialThings.length > 0
    doStuffWith specialThings

or alternatively, taking advantage of coffeescript's var safety:

if (specialThings = $ 'section .special').length
    doStuffWith specialThings

Problem

I see many people check to see if a DOM element exists before assigning an event, for example (coffeescript): ``` $ -> if( $("#progressbar").length > 0 ) $("#progressbar").progressbar( value: 0 ) ``` Is this necessary? If we just add the event anyways, whether the element exists or not, is there a performance hit?

Original source