Raw DOM element vs. jQuery object

2020-07-29 22:59发布

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?

7条回答
Root(大扎)
2楼-- · 2020-07-29 23:42

jQuery creates a "wrapped" element - a jQuery object so perhaps this will give your some insight:

$('li').each(function (index, elem) {
    alert(elem === this); // true
    alert($(this) === $(elem)); // false
    alert(elem.tagName + $(elem).tagName); // LI undefined
    alert(typeof elem + typeof $(this));// object object
    alert(elem.tagName ===  $(this).prop('tagName')); // true
});

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

$(elem).prepend('<b>' + index + ':</b>');

jquery takes the wrapped elem ($(elem)), and then prepends a NEW wrapped 'b' element with the index and ":" character as its content text

EDIT: added example of the property for tagName to the jQuery object in a further example and a prepend explanation.

查看更多
smile是对你的礼貌
3楼-- · 2020-07-29 23:42

Unlike Prototype, jQuery doesn't extend native objects. This is why you have to use $ function to get jQuery-wrapped one.

查看更多
干净又极端
4楼-- · 2020-07-29 23:44

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) available prepend being one

   $( elem ).prepend( '<b>' + index + ': </b>' );
//-^-- here this $ sign
查看更多
地球回转人心会变
5楼-- · 2020-07-29 23:48

The "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"

查看更多
【Aperson】
6楼-- · 2020-07-30 00:04

The code does not call prepend on elem, it calls it on $(elem) making it a jquery object.

查看更多
Ridiculous、
7楼-- · 2020-07-30 00:05

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 from elem.

查看更多
登录 后发表回答