Mikhail Neofitov Mikhail Neofitov - 5 months ago 8
jQuery Question

what is faster - $().closest() or native while loop?

I have my own implementation of dropdown list. I am storing all list identifiers in the global array and on

window
click event I am iterating through this array and deciding which list I have to hide.

I need to check if element has ancestor with
.active
class.

jQuery version:

for (var i = 0; i < window.dropdowns.length; i++) {
var e = window.dropdowns[i];
if ($(event.target).closest('.active').length == 0) {
e.hideList();
}
}


Pure javascript version:

for (var i = 0; i < window.dropdowns.length; i++) {
var e = window.dropdowns[i];
var parent = event.target.parentElement;
while (parent.tagName != 'BODY') {
if (parent.className.indexOf('active') > 0) {
e.hideList();
break;
}

parent = parent.parentElement;
}
}


So, what version of this will be faster? And how performance depends on number of elements on the page?

Answer

If you just want to know what's fastest, write a simple test to find out. If you want to know why...

jQuery is going to do more work than you need, for example, you are only testing tagName and className.

Having said that, your code could give you false positives because className.indexOf('active') will return > -1 if the element has a class of notactive. Use classList instead.

Finally, if you are already using jQuery, you should use it since we just showed you that code we write ourselves can be buggy, and performance is not likely to matter in this case.

Remember, premature optimization is the root of a lot of spaghetti code.

Comments