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