출처 : https://www.w3schools.com 사이트의 내용을 공부하며 정리하고 있다.

jQuery는 새로운 요소나 내용을 쉽게 추가할 수 있다.

새로운 내용을 추가(Add)하기 위해 4가지 jQuery 메소드를 찾을 수 있다.


append : 선택된 요소의 끝에 내용을 삽입한다. 

prepend : 선택된 요소의 앞쪽에 내용을 삽입한다.

after : 선택된 요소 이후에 내용을 삽입한다. 

before : 선택된 요소 이전에 요소를 삽입한다. 


1. jQuery append() 메소드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#btn1").click(function(){
        $("p").append(" <b>add text</b>");
    });
    $("#btn2").click(function(){
        $("ol").append(" <li>add li</li>");
    });
});
</script>
</head>
<body>
 
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
 
<ol>
  <li>List item 1</li>
  <li>List item 2</li>
  <li>List item 3</li>
</ol>
 
<button id="btn1">Append text</button>
<button id="btn2">Append list items</button>
 
</body>
</html>
 
 
cs


2. jQuery prepend() 메소드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#btn1").click(function(){
        $("p").prepend(" <b>add text</b>");
    });
    $("#btn2").click(function(){
        $("ol").prepend(" <li>add li</li>");
    });
});
</script>
</head>
<body>
 
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
 
<ol>
  <li>List item 1</li>
  <li>List item 2</li>
  <li>List item 3</li>
</ol>
 
<button id="btn1">Append text</button>
<button id="btn2">Append list items</button>
 
</body>
</html>
cs



함수를 활용한 append 예제

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>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function appendText() {
    var txt1 = "<p>text1</p>";
    var txt2 = $("<p></p>").text("text2");
    var txt3 = document.createElement("p");
    txt3.innerHTML = "text3";
    
    $("body").append(txt1, txt2, txt3);
}
</script>
</head>
<body>
 
<button onclick="appendText()">Append text</button>
 
</body>
</html>
 
cs


3. before( ), after( )

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#btn1").click(function(){
        $("#img1").before("before");
    });
    $("#btn2").click(function(){
        $("#img1").after("after");
    });    
});
</script>
</head>
<body>
 
<img id="img1" src="/images/w3jquery.gif" alt="jQuery" width="100" height="140"><br><br>
 
<button id="btn1">Insert before</button>
<button id="btn2">Insert after</button>
 
</body>
</html>
 
cs


+ Recent posts