Asa Carter
Asa Carter

Reputation: 2225

jQuery Select element by data value

I was using the below code to select an element by data attribute value.

The HTML code is:

...
  <li data-conversation-id="2"></li>
...

And JavaScript code:

$li = $conversations.find("[data-conversation-id='" + conversation_id + "']");

I've updated my template code and conversation-id is now set on the element via .data('conversation-id') in jQuery rather than as an inline attribute.

The .find() selector no longer works.

Upvotes: 0

Views: 347

Answers (3)

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

Use filter to check the attribute, but you'll need to select all children's. Having a selector to reduce the stack is needed for a performance gain. You can use something like this :

$li = $conversations.find("*").filter(function(){
    return $(this).data("conversation-id") == conversation_id;
});

Using '[data-conversation-id]' or 'li' instead of '*' could be a good performance gain if your elements always have that attribute or are an li.

Upvotes: 1

Ionică Bizău
Ionică Bizău

Reputation: 113335

Use .attr('data-conversation-id', yourId) to set it as inline attribute and .find(..) call will work.

Also, you can filter the elements using .filter method:

var $li = $("li").filter(function () {
    return $(this).data('conversation-id') === conversation_id;
});
// Do something with $li

filter(selector)

Description: Reduce the set of matched elements to those that match the selector or pass the function's test.

Upvotes: 0

Rimpy
Rimpy

Reputation: 888

You can use .filter() in combination with .data()

like

var li = $('li').filter(function(){
    return $(this).data('conversation-id') == conversation_id;
});

Upvotes: 0

Related Questions