How to determine whether an element exists based on id in jquery

青灯夜游
Release: 2022-05-25 14:43:06
Original
3978 people have browsed it

Judgment method: 1. Get the specified element through the id attribute value, the syntax "$("#id value")" will return a jQuery object containing the specified element; 2. Use "element object.length> 0" statement determines whether the number of elements in the specified jQ object is greater than 0. If it is greater than 0, the specified id element exists, otherwise it does not exist.

How to determine whether an element exists based on id in jquery

The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.

jquery method to determine whether an element exists based on id

1. Get the specified element through the id attribute value

$("#id值")
Copy after login

will return a jQuery object containing the specified element

2. Use the length attribute to detect whether the jQuery object exists

jQuery对象.length>0
Copy after login

The length attribute can count jquery objects The number of elements in

  • If the specified id element exists, the number of elements will be greater than or equal to 1

  • If the number is equal to 0, The specified id element does not exist

Implementation example:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="js/jquery-1.10.2.min.js"></script>
		<style>
			div,p{
				display: block;
				border: 2px solid lightgrey;
				color: lightgrey;
				padding: 5px;
				margin: 15px;
			}
		</style>

		<script>
			$(document).ready(function() {
				$("button").on("click", function() {
					var len=$("#box").length;
					console.log("id元素存在,个数为:"+len);
					$("#box").css({
						"color": "red",
						"border": "2px solid red"
					});
				});
			});
		</script>
	</head>

	<body class="ancestors">
		<div id="box">div元素</div>
		<p>p元素</p>
		<div>div元素</div>
		<button>id为“box”的元素是否存在</button>
	</body>

</html>
Copy after login

How to determine whether an element exists based on id in jquery

##[Recommended learning:

jQuery video tutorial, web front-end video

The above is the detailed content of How to determine whether an element exists based on id 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