如何使用 jQuery 移除除第一个元素之外的所有元素?
jqueryweb developmentfront end technology更新于 2026/1/15 22:22:17
要移除除第一个元素之外的所有元素,请使用 jQuery 中的 remove() 方法和 slice() 方法。您可以尝试运行以下代码,使用 jQuery 移除除第一个元素之外的所有元素 −
示例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".button1").click(function(){
$("span").remove();
});
$(".button2").click(function(){
$('span').slice(1).remove();
});
});
</script>
</head>
<body>
<button class="button2">Hide all, except first element</button>
<button class="button1">Hide all the elements</button>
<span>
<p>This is demo text.</p>
<p>This is demo text.</p>
</span>
<span>
<p>This is demo text.</p>
<p>This is demo text.</p>
</span>
<span>
<p>This is demo text.</p>
<p>This is demo text.</p>
</span>
</body>
</html>

