This article describes in detail the complete jquery processing mechanism. if you are interested, you can refer to using the jQuery selector not only to use the traditional getElementById () and getElementsByTagName () functions are much simpler and can avoid some errors. See the following example:
《script》 document.getElementById("p").style.color ="red"; 《script》
After running the code above, the browser will report an error because the webpage does not have an element with the ID of p.
The improved code is as follows:
Script if (document. getElementById ("p") {// use the IF statement to determine whether an element with an ID of p exists. IF yes, run the following code document. getElementById ("p "). style. color = "red"} script
In this way, you can avoid errors reported by the browser. However, if there are many elements to be operated on, you may have to make a judgment on each element. The jquery processing is very good, that is, using JQUERY to retrieve elements that do not exist in a webpage does not return an error.
The code is as follows:
《script》 $("#p").css("color","red"); 《script》
With this precaution, even if you delete a previously used element on a webpage for some reason in the future, you don't have to worry about the JavaScript error of this webpage.
Note:
$ ("P") is always a jquery object, even if this element is not found on the webpage. Therefore, when jquery is used to check whether an element exists on a webpage.
You cannot use the following code:
Script if ($ ("# p") {$ ("# p" ).css ("color", red) // This browser reports an error} script
It should be determined by obtaining the length.
The code is as follows:
《script》 if($("#p").length >0){ $("#p").css("color",red) }《script》
At this time, it can also be converted to a DOM object for judgment.
The code is as follows:
Ccccccc