Get first element with attribute in jQuery object, or first if none have attribute

Viewed 44

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.)

1 Answers

There are not many ways around it. It depends on how much you value the readability of your code.

What you could do, is to merge $list.filter("[data-attr]") and the $list and select the first element of the new list.

var $li = $.merge($list.filter('[data-attr]'), $list).first();

This would either return the first element with the data-attr (if one exists) or the first element of $list.

Related