I have a jQuery object that contains multiple elements, and I want the first of those elements which has a specific data attribute... BUT if none of the elements has the attribute, I want the first element from the list.
The simple solution is to use .filter("[data-attr]").first() against the object for the attribute, and if that returns .length == 0 then simply use .first()
var $list = $("li");
var $li = $list.filter("[data-attr]").first();
if ($li.length == 0) $li = $list.first();
I guess I could always do the following, but it seems very clunky...
var $list = $("li");
var $li = (($li = $list.filter("[data-attr]").first()).length == 1 ? $li : $list.first());
Is there a "nicer" way of doing this (without the use of external jQuery plugins)?
(This is not critical, and I'm happy to have the longer format of code... it's more for personal interest.)