The difference and mutual conversion between jQuery objects and DOM objects

If we want to know the difference between jQuery objects and DOM objects, we must first know their definitions:

DOM object: The object obtained by native JS is the DOM object

jQuery object: The object obtained by jQuery is called jQuery object

For example: var ele=document.querySelector('div') , the ele obtained by using native JS here is a DOM object

$('div') , the object obtained by jQuery here $('div') is a jQuery object, let's use console.dir to see what the two objects print out respectively

DOM object:

<body>
    <div></div>
    <script>
        var ele=document.querySelector('div')
        console.dir(ele)
    </script>
</body>

 jQuery object:

<body>
    <div></div>
    <script>
        console.dir($('div'))
    </script>
</body>

 in conclusion:

       By comparing the results outputted above, we can find that the jQuery object is essentially a wrapper for the DOM object and stores it in the form of a pseudo-array .

Precautions:

The jQuery object can only use the methods of the jQuery object, and the DOM object can only use the methods of the DOM object. The two cannot be mixed.

For example when hiding an element:

jQuery: Only use the hide method specific to jQuery

 <script>
        $('div').hide();
 </script>

DOM: only use style display

<script>
       var div=document.querySelector('div');
       div.style.display='none';
</script>


Interconversion of DOM objects and jQuery objects:

The purpose of mutual conversion: jQuery objects do not have as many methods as DOM objects, and DOM objects can do some things that jQuery objects cannot do, such as video playback (play()), so mutual conversion between the two is required.

Convert DOM objects to jQuery objects:

Simply put the obtained DOM object into $ for packaging

Format: $('DOM object')

<div></div>
<script>
       var ele=document.querySelector('div');
       $('ele')
</script>

Note: What you get directly is the jQuery object: $('div')


Convert jQuery objects to DOM objects:

Two formats: (index is the index number, because jQuery objects are stored as pseudo-arrays with index values)

  • $( 'element' )[ index ]
  • $( 'element' ).get( index )
<div></div>
<script>
       $('div')[0]
</script>
<div></div>
<script>
      $('div').get(0)
</script>

Guess you like

Origin blog.csdn.net/weixin_52212950/article/details/123971573