Home >Web Front-end >Front-end Q&A >How to add child nodes to the middle position in jquery

How to add child nodes to the middle position in jquery

青灯夜游
青灯夜游Original
2022-09-08 18:01:031590browse

Add steps: 1. Use the ":nth-child(n)" selector to select the child node in the middle position, the syntax is "parent element object.find(":nth-child (position value of the middle element) ")" will return a jQuery object containing the specified element; 2. Use after() to insert a new node after the middle element, the syntax is "middle element object.after (child node element)".

How to add child nodes to the middle position in jquery

The operating environment of this tutorial: windows7 system, jquery3.6.1 version, Dell G3 computer.

In jquery, you can use :nth-child(n) and after() to add child nodes to the middle position.

Implementation steps

Step 1: Use:nth-child(n) selector to select the child node in the middle position

父元素对象.find(":nth-child(中间元素的位置值)")

Will return a jQuery object containing the specified element.

Step 2: Use the after() function to insert a new node after the middle element

after() can insert a sibling node after the specified element

$(A).after(B)
  • means inserting the B sibling node behind the outside of the A node.

Implementation sample code

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="js/jquery-3.6.1.min.js"></script>
		<script>
			$(function() {
				$("button").click(function() {
					 var a = "<li style=&#39;color:red;&#39;>榴莲(新的子节点)</li>";
					$("ul").find(":nth-child(3)").after(a);
				})
			})
		</script>
	</head>
	<body>
		<ul style="border: 1px solid red;">
			<li>香蕉</li>
			<li>苹果</li>
			<li>梨子</li>
			<li>橘子</li>
			<li>桃子</li>
		</ul>
		<button>在ul的中间位置增加子节点</button>
	</body>
</html>

How to add child nodes to the middle position in jquery

Description: :nth-child() selector

:nth-child(n) selector selects all elements that are the nth child element of any type of its parent element.

:nth-child(n|even|odd|formula)
Parameters Description
n To The index of each child element that matched.

must be a number. The index number of the first element is 1.
even Select every even child element.
odd Select every odd child element.
formula Specifies which sub-element should be selected through the formula (an b).
Example: p:nth-child(3n 2) selects every third segment, starting from the second child element.

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

The above is the detailed content of How to add child nodes to the middle position 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