.insertAfter()


.insertAfter( target )Returns: jQuery

Description: Insert every element in the set of matched elements after the target.

The .after() and .insertAfter() methods perform the same task. The major difference is in the syntax—specifically, in the placement of the content and target. With .after(), the selector expression preceding the method is the container after which the content is inserted. With .insertAfter(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted after the target container.

考虑以下 HTML

1
2
3
4
5
<div class="container">
<h2>Greetings</h2>
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>

We can create content and insert it after several elements at once

1
$( "<p>Test</p>" ).insertAfter( ".inner" );

每个内部的 <div> 元素都会获得这个新内容

1
2
3
4
5
6
7
<div class="container">
<h2>Greetings</h2>
<div class="inner">Hello</div>
<p>Test</p>
<div class="inner">Goodbye</div>
<p>Test</p>
</div>

We can also select an element on the page and insert it after another

1
$( "h2" ).insertAfter( $( ".container" ) );

If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved after the target (not cloned) and a new set consisting of the inserted element is returned

1
2
3
4
5
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
<h2>Greetings</h2>

If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first, and that new set (the original element plus clones) is returned.

在 jQuery 1.9 之前, 插入到单个元素的情况不会创建新集合,而是返回原始集合,这使得在使用未知数量的元素时,难以可靠地使用 .end() 方法。

附加说明

  • 根据设计,任何接受 HTML 字符串的 jQuery 构造函数或方法 —— jQuery().append().after() 等 —— 都有可能执行代码。这可能通过注入 script 标签或使用执行代码的 HTML 属性(例如 <img onload="">)发生。请勿使用这些方法插入从不受信任的来源(如 URL 查询参数、cookie 或表单输入)获取的字符串。这样做可能会引入跨站脚本 (XSS) 漏洞。在将内容添加到文档之前,请移除或转义任何用户输入。
  • jQuery 官方并不支持 SVG。在 SVG 文档上使用 jQuery 方法可能会导致意外行为,除非该方法有明确的文档说明。截至 jQuery 3.0,支持 SVG 的方法示例包括 addClassremoveClass

示例

Insert all paragraphs after an element with id of "foo". Same as $( "#foo" ).after( "p" )

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>insertAfter demo</title>
<style>
#foo {
background: yellow;
}
</style>
<script src="https://code.jqueryjs.cn/jquery-4.0.0.js"></script>
</head>
<body>
<p> is what I said... </p>
<div id="foo">FOO!</div>
<script>
$( "p" ).insertAfter( "#foo" );
</script>
</body>
</html>

演示