Use the traditional JavaScript method as follows:
The code is as follows |
Copy Code |
if (document.getElementById (' div ')) {} else {} |
Using jquery is a simple matter of determining whether the element is 0 or not, and if 0, the element does not exist.
The jquery selector gets an element that returns an object regardless of whether the element exists
The code is as follows |
Copy Code |
var my_element=$ ("#myId"); |
Here, regardless of whether the element "myID" exists, My_element is always an object
Use the following method to determine if the "myID" element exists
The code is as follows:
The code is as follows |
Copy Code |
if ($ ("#div"). Length > 0) {//Find the element corresponding to Id=div, and then execute this block of code} |
You can even find a combination of elements, such as the following, we find an ID defined as the DIV element contains IMG, the code is as follows:
The code is as follows |
Copy Code |
if ($ ("#div img"). Length > 0) {//Find the element that corresponds to ID=DIV and contains IMG, and then execute this block of code} |
Example
The code is as follows |
Copy Code |
<div id= "Divbody" > <div id= "Divtest" ><div> </div> |
The top is simple HTML code.
code is as follows |
copy code |
JQuery ( Document). Ready (function () { if (jQuery ("#divTest"). Length > 0) { & nbsp; jQuery (" } Else { if (jQuery ("#divBody"). Length) { & nbsp; jQuery ("#divBody"). Append (" '); } } }); |
The code above shows how to tell if an object exists. The idea of the program is: if there is a divtest this Div object, Google's logo will be placed in the Divtest ID of the DIV, otherwise put the picture in Divbody. In this case, the end result of the program places the picture in divtest because of the existence of an object divtest
Attach some other methods
The second method:
The code is as follows |
Copy Code |
$ ("#myId"). HTML ("abc"); |
If myID does not exist the above code will not be wrong, just do not do any action;
The code is as follows |
Copy Code |
var data=$ ("#myId"). html (); |
If myID does not exist, data is a null value
The code is as follows |
Copy Code |
var data=$ ("#myId"). Val (); |
If myID does not exist, data is undefined