How do I iterate over jquery selector results

When I try to save all <a> elements as objects in an array (using $('a') ) and then get the position of each of them, this will not work.

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

The console says:

Uncaught TypeError: Object file: ///Users/.../index.html# does not have a 'position' method

When I do this with the only element selected by class name instead of tag name, everything works fine.

What am I doing wrong?

+7
source share
2 answers

Use this instead:

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

Also what is the meaning of year ? I prefer to name jQuery objects as follows: var $year = $("#year"); $ helps you remember the jQuery object.

+9
source

You can do the following:

 var arr = [], elems = $('a'); for(var i = 0; i < elems.length; i++){ arr[i] = elems[i]; } 
+1
source

All Articles