0

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.

1
  • can you please add a demo on jsfiddle.net Commented Jul 22, 2014 at 17:48

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

like

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.