Reputation: 2445
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
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
Reputation: 27022
You can use the attribute equals selector:
$('#menu li[data-code="sandwich"]');
Upvotes: 1