Check the performances by yourself: https://jsperf.com/ :-D That said, I guess there is no big differences, but more importantly, I have mercy on these "orphans" variables :'-( A little OOP would be more reliable:
// /my/UL.js (requires jquery.js) var my = window.my || {}; my.UL = function (id) { var me = this; var ul = $('#' + id); me.active = ul.children('.active'); ul.on('click', function (ev) { // event delegation if (ev.target.parentNode === this) { me.handleClick(ev.target); } } } my.UL.prototype.handleClick = function (li) { var me = this; me.active.removeClass('active'); me.active = $(li); me.active.addClass('active'); } my.UL.prototype.getActive = function () { // no DOM query return this.active[0]; }
Usage:
var myUL1 = new my.UL('my-favorite-ul'); var myUL2 = new my.UL('a-crappy-one'); myUL1.getActive(); // the active list item or undefined
There are three things to notice here. First, using event delegation allows to add or remove list items without worrying about the click event. Then, a fresh active property is assigned to each instance of my.UL to avoid collisions. Finally, maintaining a reference to the active item avoids to query the DOM each time you want to get the item.
However, this is not a best practice, you can find many smarter solutions over the web. I'm just trying to widen your field of vision a little. This subject is indeed more complicated than you seem to think.
Anyway, keep in mind that there are plenty of possibilities to optimize your code. Take your time :-)