0

I am trying the get an <li> element by data attribute value (data-event_id=1282).

<div id="timeline">
    <ul>
        <li class="timeline-event">
             <div>Event Body</div>
        </li>
    </ul>
</div>

$el = $('#timeline ul').find("li.timeline-event").data('event_id');
console.log($el);    // returns 1282

$el = $('#timeline ul').find("li.timeline-event[data-event_id='1282']").html();
console.log($el);    // returns undefined

What am I doing wrong?

EDIT - Solution

The data is set using .data('event_id', '1282') elsewhere in the code.

jQuery is unable to get the data if it is set using .data().

I found the solution here using the filterByData function by @psycho brm. It works!

jQuery how to find an element based on a data-attribute value?

$.fn.filterByData = function(prop, val) {
    return this.filter(
        function() { return $(this).data(prop)==val; }
    );
}

I presume this must be a jQuery bug though?

Community
  • 1
  • 1
Asa Carter
  • 2,207
  • 5
  • 32
  • 62
  • 2
    There is no data-event_id attribute in the html you provided. Please update your sample code. – Louis Huppenbauer Feb 06 '14 at 17:48
  • 1
    `.find()` never returns `undefined`, even when it doesn't find anything, it returns an empty jQuery collection. – Barmar Feb 06 '14 at 17:48
  • possible duplicate of [jQuery how to find an element based on a data-attribute value?](http://stackoverflow.com/questions/4191386/jquery-how-to-find-an-element-based-on-a-data-attribute-value) – showdev Feb 06 '14 at 17:49
  • How is it a duplicate of that? He's already using the correct selector. His problem must be something different -- he clearly hasn't posted the actual code. – Barmar Feb 06 '14 at 17:50
  • @Barmar, your right, I missed .html() from the end. Then it returns undefined. – Asa Carter Feb 06 '14 at 17:59
  • The data is set using .data() rather than inline, and that's what the issue was. – Asa Carter Feb 06 '14 at 18:02

3 Answers3

0

I don't see data- attr in your html.

I have tried your code with adding data-event_id="1282" to li http://jsfiddle.net/dehisok/Wa5RG/

 <li class="timeline-event" data-event_id="1282">

It works!

0

The data is set using .data('event_id', '1282') elsewhere in the code.

jQuery is unable to get the data if it is set using .data().

I found the solution here using the filterByData function. It works!

jQuery how to find an element based on a data-attribute value?

Community
  • 1
  • 1
Asa Carter
  • 2,207
  • 5
  • 32
  • 62
  • Add content of your refereed answer in your answer. otherwise your answer is nothing more that a link only answer which SO doesn't promote. It would be great if you provide a fiddle – Satpal Feb 06 '14 at 18:00
0

Second id return undefined because you should provide him two options with li (i) class name (ii) attribute

You should try to specify only on of them

Jain
  • 1,209
  • 10
  • 16