Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.each() and $(this)

Tags:

jquery

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 $( )?

like image 263
Randomblue Avatar asked Feb 23 '23 02:02

Randomblue


1 Answers

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.

like image 128
Dennis Avatar answered Feb 25 '23 16:02

Dennis