Below I've got two jQuery selectors.
The first searches for a DOM element within a cached object and then searches its parents, then it seaches the parents (table) for another dom element. (ex. 2)
The second (2 lines) searches via the cached element. (ex. 1)
$('element', table.setting.body).on('blur focus', table.focus).parents('parent').find('another element').on('click', function); // ex2
$('element', table.setting.body).on('blur focus', function); // ex 1
$('another element', table.setting.body).on('click', function); // ex 1
Which one is faster/best practice?
Ex. 1 would without doubt be faster reffering to jQuery functions, ie. .hide().animate().show()
but, when is it when searching for DOM elements?
The Event Loop has one simple job — to monitor the Call Stack and the Callback Queue. If the Call Stack is empty, the Event Loop will take the first event from the queue and will push it to the Call Stack, which effectively runs it. Such an iteration is called a tick in the Event Loop.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a set of events, which can trigger JavaScript code.
DOM (Document Object Model) Events are a signal that something has occurred, or is occurring, and can be triggered by user interactions or by the browser.
In my opinion this is less a question of speed but more a question of maintainability and good coding style.
And that is where Example 1 is far better than Example 2.
Avoid confusion and keep things separated. You want to attach 2 events to 2 different element - write 2 statements. This makes your code far more structured and readable.
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