How to get the data-id attribute?

Bruce Adams picture Bruce Adams · Mar 15, 2011 · Viewed 1.6M times · Source

I'm using the jQuery quicksand plugin. I need to get the data-id of the clicked item and pass it to a webservice. How do I get the data-id attribute? I'm using the .on() method to re-bind the click event for sorted items.

Answer

Marcel Jackwerth picture Marcel Jackwerth · Mar 15, 2011

To get the contents of the attribute data-id (like in <a data-id="123">link</a>) you have to use

$(this).attr("data-id") // will return the string "123"

or .data() (if you use newer jQuery >= 1.4.3)

$(this).data("id") // will return the number 123

and the part after data- must be lowercase, e.g. data-idNum will not work, but data-idnum will.