Home > Web Front-end > JS Tutorial > How to determine if id exists in jquery

How to determine if id exists in jquery

王林
Release: 2020-11-30 10:59:10
Original
2848 people have browsed it

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.

How to determine if id exists in jquery

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{}
Copy after login

or

if($("#id")[0]){} else {}
Copy after login

or directly use the native Javascript code to determine:

if(document.getElementById("id")){} else {}
Copy after login

Example:

if ($('#myElement').length > 0) { 
	// 存在
    document.write("id 为 myElement 元素存在");
} else {
	document.write("id 为 myElement 元素不存在");
}
document.write("<br>");
if ($(&#39;#xxx&#39;).length > 0) { 
	// 存在
    document.write("id 为 xxx 元素存在");
} else {
	document.write("id 为 xxx 元素不存在");
}
Copy after login

Result:

id 为 myElement 元素存在
id 为 xxx 元素不存在
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template