At first a lot of people would take the jquery selector and compare it to the two APIs (me too), but it was all right, but it made some students misunderstand the implementation of these two APIs in the browser, especially when DOM element was raised with this API.
Here's my jsfiddle example, and I'll expand on that:
JS code:
(function (global) {global.doc = document;
Global.body = Doc.getelementsbytagname (' body ') [0];
global.$ = function (ID) {return Doc.getelementbyid (ID); } Global.
Logger = function (id) {This.logelem = $ (ID);
This.logarr = [];
}; Global. Logger.prototype = {Constructor:global.logger, append:function (comment) {this.logArr.push (' <p> ' + comment + ')
</p> ');
}, Flush:function () {This.logElem.innerHTML = This.logArr.join (");
}, Clear:function () {This.logElem.innerHTML = ';
This.logarr = [];
}
};
}) (this);
(function () {var logger = new Logger (' log ');
var items = $ (' inner '). Queryselectorall (' #main h4.inside ');
Logger.append (items.length);
for (var i = 0, len = items.length i < len; i++) {logger.append (items[i].innerhtml);
} logger.flush ();
})();
(function (global) {global.doc = document;
Global.body = Doc.getelementsbytagname (' body ') [0];
global.$ = function (ID) {return Doc.getelementbyid (ID); } Global. Logger = function (ID) {this.Logelem = $ (ID);
This.logarr = [];
}; Global. Logger.prototype = {Constructor:global.logger, append:function (comment) {this.logArr.push (' <p> ' + comment + ')
</p> ');
}, Flush:function () {This.logElem.innerHTML = This.logArr.join (");
}, Clear:function () {This.logElem.innerHTML = ';
This.logarr = [];
}
};
}) (this);
(function () {var logger = new Logger (' log ');
var items = $ (' inner '). Queryselectorall (' #main h4.inside ');
Logger.append (items.length);
for (var i = 0, len = items.length i < len; i++) {logger.append (items[i].innerhtml);
} logger.flush (); })();
HTML code:
<div id= "main" >
<div id= "inner" >
CSS code:
The misconception is that the realization of the $ (' inner '). Queryselectorall (' #main h4.inside ') is understood, and many people begin to think of it directly from the children of Div[id= ' inner ' (Me too), this # Main is a bit of an eyesore. It actually looks up from the entire document according to the selector string, and then returns the child nodes belonging to div[id= ' inner '. Many people will wonder, then why not follow the parent node to find the child node directly to achieve it? Like Elem.getelementsbytagname, my idea is to be flexible selector string.
querySelector
Returns only the first element of the match, or null if there is no match.
querySelectorAll
returns a matching set of elements that, if there is no match, returns an empty nodelist (array of nodes).
And the return result is static, and subsequent changes to the document structure do not affect the results obtained before.
Currently Ie8+,ff,chrome supports this API (selector string in IE8 only supports css2.1).