Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we check if element exists before assigning events?

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?

like image 680
Craig Knox Avatar asked Jun 10 '12 18:06

Craig Knox


People also ask

How do you know if an element has an event?

To check if an element has event listener on it with JavaScript, we can call the getEventListeners function in the Chrome developer console. getEventListeners(document. querySelector("your-element-selector")); in the Chrome developer console to select the element we want to check with querySelector .

How do you know if an element has an event listener?

Right-click on the search icon button and choose “inspect” to open the Chrome developer tools. Once the dev tools are open, switch to the “Event Listeners” tab and you will see all the event listeners bound to the element. You can expand any event listener by clicking the right-pointing arrowhead.


1 Answers

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
like image 128
Ricardo Tomasi Avatar answered Oct 04 '22 09:10

Ricardo Tomasi