jQuery API 살펴보기 before 메서드

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

before() 메서드와 insertBefore() 의 차이

before() - $(target).before('내용 contentToBeInserted');

insertBefore() - $('내용 contentToBeInserted').insertBefore(target);

예제를 보면 더 잘 알게 된다.

HTML

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

스크립트

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

결과

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>

추가 인자들 ( Additional Arguments )

추가될 인자를 사용하는 방법은 .prepend(), .after(), .before() 함수들에 아래와 같은 방법으로 동일하게 적용할 수 있습니다. 인자는 DOM elements, jQuery objects, HTML strings, 그리고 DOM element 배열들을 포함합니다.

예를 들어, 두 개의 <div>를 새로 만들어 추가하려면 아래와 같이 하면 됩니다.

1
2
3
4
var $newdiv1 = $('<div id="object1"/>'),
newdiv2 = document.createElement('div'),
existingdiv1 = document.getElementById('foo');
$('p').first().before($newdiv1, [newdiv2, existingdiv1]);

추가할 수 있는 인자수는 제한이 없습니다. 또한, 위의 방법 말고 인자를 쭈욱 나열하는 방법도 있는데 위와 아래는 같은 결과를 보여줍니다.

1
$('p').first().before($newdiv1, newdiv2, existingdiv1)

예제

모든 p 태그 앞에 특정 요소를 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>before demo</title>
<style>
p {
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p> is what I said...</p>

<script>
$( "p" ).before( "<b>Hello</b>" );
</script>

</body>
</html>

모든 p 태그 앞에 DOM element를 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>before demo</title>
<style>
p {
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p> is what I said...</p>

<script>
$( "p" ).before( document.createTextNode( "Hello" ) );
</script>

</body>
</html>

모든 p 태그 앞에 jQuery object (또는 DOM elements 배열)를 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>before demo</title>
<style>
p {
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p> is what I said...</p><b>Hello</b>

<script>
$( "p" ).before( $( "b" ) );
</script>

</body>
</html>
Share