Home > Web Front-end > Front-end Q&A > Can jquery detect whether there are sibling elements?

Can jquery detect whether there are sibling elements?

青灯夜游
Release: 2022-06-08 17:15:38
Original
1748 people have browsed it

can be detected. Detection method: 1. Use the "specified element.siblings()" statement to obtain all sibling elements of the specified element, which will return a jquery object containing sibling elements; 2. Use the "jquery object.length==0" statement to determine the number of sibling elements. Whether the number is 0, if it is 0, there are no sibling elements, otherwise there are.

Can jquery detect whether there are sibling elements?

The operating environment of this tutorial: windows7 system, jquery3.2.1 version, Dell G3 computer.

Use jquery to check whether the specified element has sibling elements.

Checking method:

1. Use siblings() to get all sibling elements of the specified element

指定元素.siblings()
Copy after login

Will return a jquery object containing sibling elements.

2. Use the length attribute to get the length of the jquery object

The length obtained by the length attribute is the number of sibling elements

jquery对象.length==0
Copy after login
  • If the number of sibling elements is 0, there are no sibling elements

  • If the number is not equal to 0, there are sibling elements

Example:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<style>
			.siblings,.siblings *{ 
				display: block;
				border: 2px solid lightgrey;
				color: lightgrey;
				padding: 5px;
				margin: 15px;
			}
		</style>
		<script src="js/jquery-3.2.1.min.js"></script>
		<script type="text/javascript">
			$(document).ready(function() {
				$("button").click(function() {
					var len=$("h2").siblings().length;
					if(len==0){
						console.log("h2没有同胞元素"); 
					}else{
						console.log("h2有同胞元素,其个数为:"+len); 
					}
	
				});
			});
		</script>
	</head>
	<body>
		<div class="siblings">div (父)
			<p>p(兄弟元素)</p>
			<span>span(兄弟元素)</span>
			<h2>h2(本元素)</h2>
			<h3>h3(兄弟元素)</h3>
			<p>p(兄弟元素)</p>
		</div>
		<button>检测h2是否有同胞元素</button>
	</body>
</html>
Copy after login

Can jquery detect whether there are sibling elements?

[Recommended learning: jQuery video tutorial, web front-end video]

The above is the detailed content of Can jquery detect whether there are sibling elements?. 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