The jquery selector draws on the CSS selector, and the core still relies on JavaScript's getElementById () and getElementsByTagName () methods, but he encapsulates 2 ways to make the jquery selector simple and easy to use.
And it avoids the problem of error-prone.
The jquery selector returns an array object and returns an empty array if the specified element is not found.
So when you decide if a jquery object exists, you can't use the following statement
if ($ ("tr")) {//code}
Instead, the array length should be used to determine the following statement
if ($ ("tr"). Length > 0) { //code }
If you use the getElementById () and getElementsByTagName () methods, it is easy to throw exceptions, because JavaScript does not have a built-in class selector method, and now extends a class selector method to explain why the exception was thrown
document.getelementsbyclassname = function (className) { var el = []; _el = document.getElementsByTagName (' * '); // get all elements for (var i = 0;i < _el.length; i++) {// if (_el[i].classname = = className) {// Gets the element of the same class name El[el.length] = _el[i]; }} return El; }
If the passed-in class name is not found, then EL is a null value. The return is an exception.
After encapsulating the Getelementsbyclassname () method, you can use it as a built-in JavaScript selector! (--pretend to be built-in!!) )
<!doctype html>Document.getelementsbyclassname=function(className) {varEl = []; _el= document.getElementsByTagName (' * ');//Get all elements for(vari = 0;i < _el.length; i++){ if(_el[i].classname = =className) {El[el.length]=_el[i]; } } returnel; } window.onload=function() { varRed = Document.getelementsbyclassname ("Red"); for(vari = 0;i< red.length;i++) {Red[i].style.color= "Red"; } } </script>While this custom method works the same as the jquery selector, using the custom Getelementsbyclassname () method is not as good as the jquery selector in terms of execution efficiency. Because as a jquery technical framework, his code is optimized to perform faster than a custom method (execution efficiency is very important)
Little tricks!
The tradeoff between code execution efficiency and programmer development efficiency is that you can combine JavaScript native methods with jquery iterative operations and not write much code
<script type= "Text/javascript" src= "jquery1.8.2.js" ></script><script type= "Text/javascript" > $ (function() { var all = document.getElementsByTagName ("*"); JavaScript Native notation, gets the element collection $ (All). CSS ("Color", "red"); jquery notation font color })</script>
Reference from the "jquery Full development Technology Treasure"
Tips and exceptions for JQuery selectors and JavaScript selectors