Home > Web Front-end > Front-end Q&A > How to clear unselected elements at the same level in jquery

How to clear unselected elements at the same level in jquery

青灯夜游
Release: 2022-05-26 14:04:35
Original
1316 people have browsed it

Clearing method: 1. Use siblings() to obtain all other sibling elements of the selected element. The syntax "specify element.siblings()" will return a jquery object containing all sibling elements; 2. Use remove() deletes the obtained sibling element, the syntax is "sibling element object.remove()".

How to clear unselected elements at the same level in jquery

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

jquery method to clear non-selected elements at the same level

1. Use siblings() to select all other siblings of the selected element. Element

siblings() method is mainly used to obtain all elements at the same level of the specified element.

$(selector).siblings()
Copy after login

will return a jquery object containing all sibling elements.

2. Use remove() to delete the obtained sibling elements.

同级元素对象.remove()
Copy after login

The remove() method removes the selected elements, including all text and child nodes. This method also removes data and events from the selected element.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<script src="js/jquery-1.10.2.min.js"></script>
		<style>
			.siblings * {
				display: block;
				border: 2px solid lightgrey;
				color: lightgrey;
				padding: 5px;
				margin: 15px;
			}
		</style>
		<script>
			$(document).ready(function() {
				$("li.start").css({
					"color": "red",
					"border": "2px solid red"
				});
				$("button").click(function() {
					$("li.start").siblings().remove();
				});
			});
		</script>
	</head>
	<body>

		<div style="width:500px;" class="siblings">
			<ul>ul (父节点)
				<li>li (类名为"star"的上一个兄弟节点)</li>
				<li>li (类名为"star"的上一个兄弟节点)</li>
				<li class="start">类名称为“star”的li元素</li>
				<li>li (类名为"star"的下一个兄弟节点)</li>
				<li>li (类名为"star"的下一个兄弟节点)</li>
			</ul>
		</div>
		<p>选择类名称为“star”的li元素的所有兄弟元素</p>
		<button>清除同级非选中的元素</button>
	</body>
</html>
Copy after login

How to clear unselected elements at the same level in jquery

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

The above is the detailed content of How to clear unselected elements at the same level 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