jabber1111 jabber1111 - 21 days ago 6
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() {

run($('.stickable'));
})

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

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


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

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
Comments