Home >Web Front-end >Front-end Q&A >How to find the number of sibling elements in jquery

How to find the number of sibling elements in jquery

青灯夜游
青灯夜游Original
2022-05-16 16:17:402155browse

Obtaining method: 1. Use siblings() to obtain the sibling elements of the specified element. The syntax "specified element.siblings()" will return a jQuery object containing all sibling elements; 2. Use the length attribute to count and combine Returns the number of elements in the jQuery object, the syntax is "specify object.length".

How to find the number of sibling elements in jquery

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

jquery method to find the number of sibling elements

1. Use the siblings() method to get all the brothers of the selected element Element

This method traverses forward and backward along the sibling elements of the DOM element.

指定元素.siblings()

will return a jQuery object containing all sibling elements.

2. Use the length attribute to get the number

The length attribute will count the number of elements in the jQuery object and return it.

指定对象.length

Implementation 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-1.10.2.min.js"></script>
		<script type="text/javascript">
			$(document).ready(function() {
				$("button").click(function() {
					$("h2").siblings().css("border","2px solid red")
					var len=$("h2").siblings().length;
					console.log("兄弟元素的个数为:"+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>获取兄弟元素的个数</button>
	</body>
</html>

How to find the number of sibling elements in jquery

[Recommended learning: jQuery video tutorial, web Front-end video

The above is the detailed content of How to find the number of sibling elements 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