Fred J. Fred J. - 1 year ago 77
Javascript Question

Get data attribute value of the Nth element using jQuery

I am trying to get the

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


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

Yet it works with this:


What if I want to use the Nth element? Thanks

Answer Source

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.