Curious Curious - 7 months ago 18
Javascript Question

jQuery selectors and .each()

Why are the objects returned by a selector (for example

$("div")
) different from the objects you get by looping through the result of the selector with the
.each()
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")


and

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





Note



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

Answer

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.


Demo

var data = [];
$.each($("div"), function(index, value) {
    data.push({
        '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="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<div id="test1">
  <div id="test2">
     Hello
  </div>
</div>
<div id="test3">
     World
</div>
<div id="test4">
    <div id="test5">
    </div>
    <div id="test6">
        <div id="test7">
        </div>
    </div>
</div>