I'm looking at the following example of explicit iteration from http://jqfundamentals.com/chapter/jquery-basics:
$( 'li' ).each(function( index, elem ) {
// this: the current, raw DOM element
// index: the current element's index in the selection
// elem: the current, raw DOM element (same as this)
$( elem ).prepend( '<b>' + index + ': </b>' );
});
The comments refer to elem
as a raw DOM element, but then the code calls .prepend()
on elem
.
I'm just getting started with jQuery, but it's my understanding you can only call a jQuery method on a jQuery object - not on a raw DOM element. Am I misunderstanding?
jQuery creates a "wrapped" element - a jQuery object so perhaps this will give your some insight:
Notice that second alert = false, so even though they "refer" to the same element, $(this) and $(elem) are NOT the same wrapped object. Notice that the "raw" elem has a .tagName whereas the jQuery wrapped object does not.
SO for your
jquery takes the wrapped elem (
$(elem)
), and then prepends a NEW wrapped 'b' element with the index and ":" character as its content textEDIT: added example of the property for tagName to the jQuery object in a further example and a prepend explanation.
Unlike Prototype, jQuery doesn't extend native objects. This is why you have to use
$
function to get jQuery-wrapped one.you are converting the raw DOM element to jquery object again.. see the first $ sign in the the
elem
.elem
is raw but$(elem)
is jquery object and thus you can use any jQuery function(methods) availableprepend
being oneThe "elem" in the example above could be any tag (h1, p, body, a combination of tags, a specific reference to an id or class) Just like CSS. Then "prepend" is the action performed on that element. In this case the prepend action take one parameter, which is another element that will be dynamically placed into the html as the first child element for every element on the page that matches your selected "elem"
The code does not call
prepend
onelem
, it calls it on$(elem)
making it a jquery object.elem
is a raw DOM element. By wrapping elem$(elem)
you are creating a jQuery object from the raw DOM element. jQuery allows you to do this. You are then calling.prepend()
on the jQuery object created fromelem
.