Closest (filter) Returns the first ancestor of the selected element: $(selector).closest(filter)

Closest (Filter,context) returns the first ancestor element in the DOM tree searched using DOM Context: Context: Context, scope $(selector). Closest (filter,context)

The filter required. A selector expression, element, or jQuery object context that Narrows the search for ancestor elements is optional. Within this you can find the DOM element that matches the element


Closest () runs up the DOM tree starting with the current element and returns the first single ancestor of the expression that was passed according to the match. Returns a jQuery object containing zero or one element that runs up the DOM tree until a match to which the selector has been applied can’t be empty

Parents () iterates up the DOM tree starting with the parent element and returns all ancestors that match the expression passed. Returns a jQuery object containing zero, one, or more elements iterating up the DOM tree to the root element of the document, adding each ancestor element to a temporary collection; If a selector is applied, the collection is filtered based on that selector and the parameter can be null


<! DOCTYPEhtml>
<html xmlns:th="http://www.thymeleaf.org">

	<head>
		<meta http-equiv="Cache-Control" CONTENT="no-cache" />
		<meta http-equiv="Pragma" CONTENT="no-cache" />
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<title>According () a simple example</title>
		<style type="text/css">
			li { margin: 3px; padding: 3px; background: #EEEEEE; }
			.hilight { background: yellow; }
		</style>
	</head>

	<body>

		<ul id="one" class="level-1">
			<li class="item-i">I</li>
			<li id="ii" class="item-ii">II
				<ul class="level-2">
					<li class="item-a">A</li>
					<li class="item-b">B
						<ul class="level-3">
							<li class="item-1">We can pass a DOM element as a context and search for the closest element in it</li>
							<li class="item-2">It's a context</li>
							<li class="item-3">.closest('ul', context)</li>
						</ul>
					</li>
					<li class="item-c">C</li>
				</ul>
			</li>
			<li class="item-iii">III</li>
		</ul>

	</body>

	<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
	<script type="text/javascript" th:inline="javascript">
		$(document).bind("click".function(e) {
			$(e.target).closest("li").toggleClass("hilight");
		});

		var listItemII = document.getElementById('ii');
		$('li.item-a').closest('ul', listItemII).css('background-color'.'red');
		$('li.item-a').closest('#one', listItemII).css('background-color'.'green');
	</script>

</html>
Copy the code

end