Curious Curious - 5 months ago 8
Javascript Question

jQuery selectors and .each()

Why are the objects returned by a selector (for example

) different from the objects you get by looping through the result of the selector with the
function? I do not think I understand the exact semantics of either function. Could someone clarify why they are different? In particular if I form an array manually, why can I not call the same methods on objects of that array?

For example printing the values in the array for the two cases yields different results

array = $("div")


array = [];
$.each($("div"), function(index, value) {


Turns out that they are in fact the same. The difference was being cause for some reason because of the browser cache. Cleaning up the cache made this work


Within your function, you can call this to reference to the element that function applies to!

You can wrap $() around this ($(this)) if you feel more comfortable working with jQuery objects.

The index parameter of your function corresponds with the position of the element in the list of selected elements.

The value parameter of your function corresponds with the element, which basically means that this and value have the same value.


var data = [];
$.each($("div"), function(index, value) {
        'index' : index,
        'this' : $(this).attr("id"),
        'value' : $(value).attr("id")

document.body.innerHTML = '<pre>' + JSON.stringify(data, undefined, 2) + '<pre>';
<script type="text/javascript" src=""></script>
<div id="test1">
  <div id="test2">
<div id="test3">
<div id="test4">
    <div id="test5">
    <div id="test6">
        <div id="test7">