.each () and $ (this)

This is my code:

$myDiv = $('<div>1</div>'); $myDiv.each(function () { console.log(this.html()); }); 

It throws an error because this must be $(this) . But wait. The $myDiv is not a jQuery object, so this should also be a jQuery object. If so, why should I wrap this inside $( ) ?

+4
source share
6 answers

The jQuery object is more or less an array of regular DOM elements. each iteration over them. this is just a DOM element, while $(this) generates a singleton array of DOM elements with access to jQuery API functions.

+6
source

In this case, this actually refers to node.

 $myDiv = $('<div>1</div>'); $myDiv.each(function () { console.log(this.innerHTML); }); // outputs 1 
+1
source

Basically, everything that is selected as $() becomes part of the array, which jQuery adds helper methods to it, the .each() method .each() over each element of the array. That is, it is just an element, not a jQuery array, which has all the useful helper methods.

+1
source

As I understand it, this is a DOM object. Try this code to see:

$myDiv = $('<div>1</div>'); $myDiv.each(function () { alert(this.nodeName); });

0
source

According to the jquery documentation, this is the expected behavior for $(selector).each() They even give you an example for the case where โ€œyou want to have a jQuery object instead of a regular DOM elementโ€: http://api.jquery.com/each/ # example-1

0
source

When you create an HTML object in jQuery, like you, it returns a DOM element. If you really wanted to set the HTML for your new dom element, you would need to call the innerHTML property as follows:

 $myDiv.each(function () { console.log(this.innerHTML); }); 

For reference, here is the jQuery API for creating DOM elements: http://api.jquery.com/jQuery/#jQuery2

Also, I'm not sure why you called each function for only one element that was just created?

0
source

All Articles