0){}else{}]. If length>0, it means that the id exists. Otherwise, it means that the id does not exist."/> 0){}else{}]. If length>0, it means that the id exists. Otherwise, it means that the id does not exist.">

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

How to determine if id exists in jquery

王林
王林Original
2020-11-26 10:25:502900browse

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{}

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 ($(&#39;#xxx&#39;).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!

Statement:
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