jQuery API 살펴보기 insertBefore 메서드

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

before() 메서드와 insertBefore()메서드는 동일한 기능을 수행한다. 중요한 차이점은 요소에 들어갈 내용과 대상의 위치 차이이다.

이것 또한 after()와 insertAfter() 와 똑같은 말이다. 들어갈 내용(컨텐츠)가 앞에 들어가야 되는게 insertBefore() 뒤에 들어가야되는게 before()

또 똑같은 예제를 보면 안다.

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>" ).insertBefore( ".inner" );

결과 - inner 클래스를 가진 요소의 앞 요소에 컨텐츠가 추가되었다.

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

예제

id가 foo인 요소 앞에 p 태그를 추가한다. before를 사용하면 $(“#foo”).before(“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>insertBefore demo</title>
<style>
#foo {
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<div id="foo">FOO!</div>
<p>I would like to say: </p>

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

</body>
</html>
Share