I need to call a function on a DOM element automatically. The following code works, but I wonder if there's a better way.
$('#toc > ul > li').first().find('a').each(loadTopic);
My selectors will return exactly one element, so running "each" seems hackish. Is there a better way to call 'loadTopic' on my anchor element?
Using .each
is about as good as it gets here, not least because it automatically passes the native DOM elements from within the jQuery object, and not wrapped up as jQuery objects themselves. Heck, it even sets this
to be that element for you.
You could implement a .call()
plugin that only works on the first element in a jQuery object, but it would be kinda pointless...