jabber1111 jabber1111 - 9 months ago 40
jQuery Question

javascript object contains divs with custom 'data' but I can't view data

I've got the following code snippet:

$(window).load(function() {


var run = function (headers){
var $window = $(window)
var $headers

$headers = headers.each(function(){
var $currentHeader = $(this).wrap('<div class="followWrap">');
.data('startPosition', $currentHeader.offset().top)
.data('headerHeight', $currentHeader.outerHeight())

When I place a debugger and console $headers I get what looks like an array of divs. However typeof shows this is an object. When I try $headers.data() I get the startPosition and headerHeight of first div. When I try $headers[2] I get the second div. When I try $headers[2].data() I get an error. When I do a $.each loop I get the correct info. My question is why can't I state $headers[2].data(), or simply select any div and show it's data?

Answer Source

It's because accessing a jQuery object by index returns a DOMElement, not another jQuery object, hence the data() method doesn't exist. Use eq() to get a jQuery object by index:

var data = $headers.eq(1).data(); // zero-based index, 2nd item = index 1