Fred J. Fred J. - 6 months ago 35
Javascript Question

Get data attribute value of the Nth element using jQuery

I am trying to get the

data
attribute value of the first element from the
elements
matched by this jQuery selector but it is giving me an error:

$("p.expiryItem").get(0).attr("data-id")



Uncaught TypeError: $(...).get(...).attr is not a function(…)


Yet it works with this:

$("p.expiryItem").attr("data-id")


What if I want to use the Nth element? Thanks

Answer

The problem is because although get(N) returns the Nth element in the matched set, it returns the underlying DOMElement which does not have an attr() method and hence the error.

To fix this you could use eq() which does the same job, but returns the element in a jQuery object:

$("p.expiryItem").eq(0).data('id') // zero-based

Or you could use the :nth-child selector:

$("p.expiryItem:nth-child(1)").data('id') // one-based

Note the preferred use of data() here to retrieve the data-* attribute.