-1

Possible Duplicate:
jquery data selector

I have several elements with class 'connection_name'. Each one of these elements has a unique id bound to it using the data() JQuery function. I'm trying to query to find the element with a given id, but I can't seem to get it to work.

For the sake of this test, I created a page with only 1 element, and set the id of the element.

I can verify that the id is being set, as when I query the element in the console, it shows the id returned:

$('.connection_name').data()
  Object
  id: "4fea76bd99ea080d19000002"
  __proto__: Object

I've read on other questsions/posts that the element should be selected by $('selector[data-attribute=value]'), but that doesn't seem to work:

$('.connection_name[data-id="4fea76bd99ea080d19000002"]')
[]

Worse than that, even when I try to select it without any value (just by the attribute), I still return nothing:

$('.connection_name[data-id]')
[]

I'm not sure what the issue is, or how to go about doing this.

Community
  • 1
  • 1
Ryan Ogle
  • 726
  • 1
  • 7
  • 16

1 Answers1

7

Here's one way to do it:

var theItem = $('.connection_name').filter(function() {
    return($(this).data("id") === "4fea76bd99ea080d19000002");
});
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • This works well, thanks jfriend. Do you happen to know why the $('selector[data-attribute=value]') pattern doesn't work? Several sources seem to claim that it does. Thanks again. – Ryan Ogle Jul 01 '12 at 01:46
  • They're two different things. If you set data-* attributes on the elements, jQuery reads them ONCE, at document ready, and syncs them to its internal data storage. If you update these values later, using `.data()`, the attributes will not change. In the same way, if you update the data-* attributes using `.attr()`, the jQuery internal data storage will not change. So instead you have to iterate over every single element that fits your criteria, and read its data. – Interrobang Jul 01 '12 at 02:11
  • @RyanOgle - When you do an attribute selector, that ONLY reads attributes from the actual DOM object, thus `'.connection_name[id="4fea76bd99ea080d19000002"]'` will only work if there is a data-id attribute on the object with that value. This will only be the case if the attribute is present in the HTML or if it is set with `.attr()`. If it the id value is set with `.data("id", "4fea76bd99ea080d19000002")`, then the value is NOT set as an attribute on the object (it's set in an internal data structure inside of jQuery) and thus it will not be found by a selector operation. – jfriend00 Jul 01 '12 at 06:00