jQuery gets the previous, next, parent element, and child element of an element (study notes)

1. Problem description

1. First is this HTML structure:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Title</title>
	<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
	<div id="parent">
		<div id="firstSon">
			<span id="notSelect">其他</span>
		</div>
		<div id="secondSon">
			<div id="nowSelect">
				<span id="grandSon">当前</span>
			</div>
		</div>
			<div id="firstSon">
			<span id="notSelect">其他</span>
		</div>
	</div>
</body>
</html>

2. First, the jQuery selector points to the div element with id="nowSelect"

JS code using jQuery statement:

<script>
	var selectObj = $("#nowSelect");
	console.log(selectObj[0]);
</script>

operation result:

<div id="nowSelect">
	<span id="grandSon">当前</span>
</div>

2. Get other elements

1. Get its parent element (.parent())

Code:

<script>
	var selectObj = $("#nowSelect").parent();
	console.log(selectObj[0]);
</script>

operation result:

<div id="secondSon">
	<div id="nowSelect">
		<span id="grandSon">当前</span>
	</div>
</div>
注:
(1)jQuery.parents(expr)类似于jQuery.parents(expr),但是是查找所有祖先元素,不限于父元素;
(2)jQuery.parent()可以传入expr进行过滤(jQuery.parent(expr)),比如$("span").parent()或者$("span").parent(".class").

2. Get its child elements (.children())

Code:

<script>
	var selectObj = $("#nowSelect").children();
	console.log(selectObj[0]);
</script>

operation result:

<span id="grandSon">当前</span>

3. Get its previous element (.prev())

Code:

<script>
	var selectObj = $("#nowSelect").parent().prev();
	console.log(selectObj[0]);
</script>

operation result:

<div id="firstSon">
	<span id="notSelect">其他</span>
</div>
注:jQuery.prevAll()返回所有之前的兄弟节点

4. Get its next element (.next())

Code:

<script>
	var selectObj = $("#nowSelect").parent().next();
	console.log(selectObj[0]);
</script>

operation result:

<div id="thirdSon">
	<span id="notSelect">其他</span>
</div>
注:jQuery.nextAll()返回所有之后的兄弟节点

5. Get the nearest element whose attribute is XXX (.closest())

Code:

<script>
	var selectObj = $("#grandSon").closest("div");
	console.log(selectObj[0]);
</script>

operation result:

<div id="nowSelect">
	<span id="grandSon">当前</span>
</div>

3. Others

1. Find the first child element of the same parent (.first())

Code:

<script>
	var selectObj = $("#parent div").first();
	console.log(selectObj[0]);
</script>

operation result:

<div id="firstSon">
	<span id="notSelect">其他</span>
</div>

2. Find the last child element of the same parent (.last())

Code:

<script>
	var selectObj = $("#parent div").last();
	console.log(selectObj[0]);
</script>

operation result:

<div id="thirdSon">
	<span id="notSelect">其他</span>
</div>

Guess you like

Origin blog.csdn.net/weixin_47278656/article/details/130022280
Recommended