12

When I'm trying to store all <a> elements as objects in array (using $('a')), and then get the position of each of them, it doesn't work.

years = $('a');
for(i=0;i< years.length;i++){
   if(years[i].position().top > year.position().top){

   }
   else{

   }
}

Console says:

Uncaught TypeError: Object file:///Users/.../index.html# has no method 'position'

When I do it with single element selected by class name instead of tag name, everything works fine.

What am I doing wrong ?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Michael
  • 723
  • 6
  • 18

2 Answers2

14

Use this instead:

$("a").each(function() { 
  var pos = $(this).position();
  if (pos.top > year.position().top) {
     // hurray
  }
});

Also what is the value of year? I prefer to name jQuery objects like this: var $year = $("#year"); The $ helps you remember it's a jQuery object.

JeffThompson
  • 1,538
  • 3
  • 24
  • 47
Jamund Ferguson
  • 16,721
  • 3
  • 42
  • 50
1

You can do the following:

var arr = [], elems = $('a');

for(var i = 0; i < elems.length; i++){
   arr[i] = elems[i];
}
Headshota
  • 21,021
  • 11
  • 61
  • 82