The difference between querySelector and $()
The
page has the following elements
<div class="list-box">
<div class="buttonrideo">
<input id="aBtn" type="checkbox" class="default-1"/>
</div>
</div>
<div class="list-box">
<div class="buttonrideo">
<input id="bBtn" type="checkbox" class="default-1"/>
</div>
</div>
jquery script:
var a = document.querySelector("-sharpaBtn");
var b = $("-sharpaBtn");
What"s the difference between
an and b? Found that b [0] = = a, why?
document.querySelector is the browser-level API, that selects the first satisfied DOM node based on the parameters.
The $in the
jquery script can only be used after introducing jquery, which is also the selector of dom. Select an array of DOM nodes that meet the conditions. Now jquery seems to be the native DOM element, so $('- sharpaBtn') [0]
is equivalent to document.querySelector ('- sharpaBtn')
.
- an is the DOM native element object returned by (calling querySelector)
- b is the jQ wrapper object returned by calling jQ's $/ jQuery, or jQuery constructor. The jQ wrapper object contains both native DOM objects and some jQ's own things
-
b [0] = = a
because the jQ wrapper object stores the native DOM object in the location of key [0] (which you'll know as soon as you console)
an is a js object, b is a jquery object
third-class
and ok, $('- sharpdom') [0]
has indeed become a complete dom object
suggest that the owner take a look at the DOM object and jQuery object and how to convert them into
.
- document.querySelector () browser, which is queried as
DOM object
The API, query provided by - $() for jQuery comes out as a jQuery object, and the
jQuery object [0] is equal to the corresponding DOM object
.
first of all, the $()
function is in the JQuery class library, and querySelector ()
is included in html5.
The behavior of
$()
is to find all matching elements and encapsulate them into jQuery objects for ease of use. The behavior of
querySelector ()
is to find the first element that matches, and the returned value is the native DOM object.
using the square bracket operator on the jQuery object returns the native DOM object, so b [0]
returns the first native DOM object that matches the selector, so it is equal to the value a
returned by querySelector ()
.
then there is a querySelectorAll ()
method in html5, which returns a NodeList
object that can be iterated over. The behavior of this method may be more similar to jQuery's $()
.
let a = document.querySelectorAll('-sharpaBtn');
let b = $('-sharpaBtn');
a[0] === b[0]; //