Home  >  Article  >  Web Front-end  >  How to query the last child element with jquery

How to query the last child element with jquery

青灯夜游
青灯夜游Original
2022-05-13 18:29:149291browse

Two methods: 1. Use children() and ":last-child" selector, syntax "$(parent element).children(":last-child")". 2. Use children() and eq(), the syntax is "$(parent element).children().eq(-1)".

How to query the last child element with jquery

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

Two methods for jquery to query the last child element

Method 1: Use children() and:last-childselector

  • Use children() to get all direct child elements under the specified parent node

  • Use:last-child to select the last element in the child element collection, that is, the last child element

Example:

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<script src="js/jquery-1.10.2.min.js"></script>
		<script>
			$(function () {
            $("button").click(function () {
				$("ul").children(":last-child").css("color","red");
            })
        })
    </script>
	</head>
	<body>
		<ul>
			<li>香蕉</li>
			<li>苹果</li>
			<li>梨子</li>
			<li>橘子</li>
		</ul>
		<button>父元素ul的最后一个子元素</button>
	</body>
</html>

How to query the last child element with jquery

Method 2: Use children() and eq()

  • Use children() to get all direct child elements under the specified parent node

  • Use eq(-1) to select the last element in the sub-element set, that is, the last sub-element

Based on the above example, modify:

$(function() {
	$("button").click(function() {
		$("ul").children().eq(-1).css("color", "red");
	})
})

How to query the last child element with jquery

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

The above is the detailed content of How to query the last child element with 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