jQuery API 살펴보기 insertAfter 메서드

조건에 일치되는 target 요소 뒤에 추가될 내용(요소)를 삽입한다.

‘after’는 선택자 다음에 인수를 삽입합니다. ‘insertAfter’는 인수 뒤에 선택기를 삽입합니다. A.after(B)라면 A 뒤에 B를 추가하는 것이고 A.insertAfter(B)는 B 뒤에 A를 추가하는 겁니다.

.after ().insertAfter () 메서드는 동일한 작업을 수행합니다. 주요 차이점은 구문과 특히 콘텐츠 및 대상의 배치에 있습니다.

아래의 HTML은 after() 메서드를 설명할 때 사용한 HTML과 똑같다. 그럼 어떤 부분에서 다른지 살펴보자.

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

스크립트

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

눈치를 챘는지는 모르겠지만 () 안에 인수의 내용이 뒤바뀌었다. after() 메서드는 삽입할 대상이 뒤에 가있지만 insertAfter() 메서드는 삽입할 대상이 앞에 먼저 나와있다. 나머지는 기능이 거의 같은 것 같다.

after() 메서드일때

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

예제

id=”foo”를 p 태그 뒤에 삽입한다. after를 사용할 경우 $(“#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.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p> is what I said... </p>
<div id="foo">FOO!</div>

<script>
$( "p" ).insertAfter( "#foo" );
</script>

</body>
</html>
Share