How jquery determines whether an id exists: You can use the length attribute of the jquery object to determine, such as [if($("#id").length>0){}else{}], if length> 0 means that the id exists, otherwise it means that the id does not exist.
The operating environment of this tutorial: Windows 10 system, jquery version 2.2.4. This method is suitable for all brands of computers.
(Learning video sharing: jquery video tutorial)
The judgment method is as follows:
Use the length attribute of the jQuery object to judge, if > 0 Just exists.
if($("#id").length>0){}else{}
or
if($("#id")[0]){} else {}
or directly use the native Javascript code to determine:
if(document.getElementById("id")){} else {}
Example:
if ($('#myElement').length > 0) { // 存在 document.write("id 为 myElement 元素存在"); } else { document.write("id 为 myElement 元素不存在"); } document.write("<br>"); if ($('#xxx').length > 0) { // 存在 document.write("id 为 xxx 元素存在"); } else { document.write("id 为 xxx 元素不存在"); }
Result:
id 为 myElement 元素存在 id 为 xxx 元素不存在
Related recommendations: js tutorial
The above is the detailed content of How to determine if id exists in jquery. For more information, please follow other related articles on the PHP Chinese website!