Ken Palmer
Ken Palmer

Reputation: 2445

With jQuery, how can I select a single list item by data attribute and by that list's ID?

What is the correct jQuery syntax to select a list item by a data attribute in a specified list? Here is a sample list:

<ul id="menu">
<li data-code="soup">Soup</li>
<li data-code="salad">Salad</li>
<li data-code="sandwich">Sandwich</li>
</ul>

From the above, I'd like to use both the ID for the list and the data-code that is applied to the list item in the selector. Initially I thought something like this would work, but it's not.

var $menuItem = $('#menu li').attr('data-code', 'sandwich');

The interface I'm working on is more complex than this example, hence my reason for wanting to incorporate the ID in the selector. Thanks for your help.

Upvotes: 1

Views: 473

Answers (2)

FastTrack
FastTrack

Reputation: 8980

You're looking for the Attribute Equals Selector:

var $menuItem = $("#menu li[data-code='sandwich']");

We are referencing all li elements inside #menu whose attribute data-code equals sandwich.

Upvotes: 0

Jason P
Jason P

Reputation: 27022

You can use the attribute equals selector:

$('#menu li[data-code="sandwich"]');

Upvotes: 1

Related Questions