Home >Web Front-end >Front-end Q&A >How to remove the last node in jquery

How to remove the last node in jquery

青灯夜游
青灯夜游Original
2022-04-22 17:55:282671browse

Method to remove the last node: 1. Use the "eq(-1)" selector to select the last node in the document, the syntax is "$(Element:eq(-1))"; 2 . Use remove() to delete the selected node. The syntax "selected element.remove()" can delete the specified element and all text and sub-nodes inside it.

How to remove the last node in jquery

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

jquery removes the last node

Implementation method:

  • Use the ":eq()" selector to select the last node element in the document

  • Use remove() to delete the selected node element

    remove() method Deletes an element and all content within it.

Key points: :eq() selector

  • : The :eq() selector selects elements with the specified index value.

  • index values ​​start at 0, so the index value of the first element is 0 (not 1).

  • When the index is a negative value, select the element from back to front

Implementation code:

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

		<script>
			$(document).ready(function() {
				$("button").on("click", function() {
					$("li:eq(-1)").remove();
				});
			});
		</script>
	</head>

	<body class="ancestors">
		<div style="width:500px;">div (父节点)
			<ul>ul (指定元素)
				<li>li (子节点1)
					<span>span (孙节点1)</span>
				</li>
				<li>li (子节点2)
					<span>span (孙节点2)</span>
				</li>
				<li>li (子节点3)
					<span>span (孙节点3)</span>
				</li>
			</ul>
		</div>
		<button>删除最后一个li元素</button>
	</body>

</html>

How to remove the last node in jquery

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

The above is the detailed content of How to remove the last node 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