Randomblue
Randomblue

Reputation: 116263

.each() and $(this)

This is my code:

$myDiv = $('<div>1</div>');

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

It produces an error because this should be $(this). But wait. Isn't $myDiv a jQuery object in the first place, so that this must also be a jQuery object. If so, why should I wrap this inside of $( )?

Upvotes: 4

Views: 1713

Answers (6)

bittersweetryan
bittersweetryan

Reputation: 3443

When you create an HTML object in jQuery like you did it returns the DOM element. If you really wanted to set the HTML of your new dom element you'd have to call the innerHTML property like so:

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

For reference here's the jQUery API on creating DOM elements: http://api.jquery.com/jQuery/#jQuery2

Also, I'm not sure why you'd call the each function on a single element that has just been created?

Upvotes: 0

vitorbal
vitorbal

Reputation: 3031

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

Upvotes: 0

Ali
Ali

Reputation: 12664

Basically anything fetched as $() becomes part of an array which jQuery adds it's helper methods to, the .each() method actually iterates over each element in the array. That is, it's just the element and not the jQuery array that has all the nice helper methods.

Upvotes: 1

Blazemonger
Blazemonger

Reputation: 92893

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

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

Upvotes: 0

Dennis
Dennis

Reputation: 32598

A jQuery object is more or less an array of regular DOM elements. each iterates over these. this is just a DOM element whereas $(this) generates a one-element array of DOM elements with access to the jQuery API functions.

Upvotes: 6

cwallenpoole
cwallenpoole

Reputation: 81988

In that case this actually refers to the node.

$myDiv = $('<div>1</div>');

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

Upvotes: 1

Related Questions