jQuery / Method / .insertAfter() - 선택한 요소 뒤에 새 요소를 추가하거나, 다른 곳에 있는 요소를 이동시키는 메서드
.insertAfter()는 특정 요소 뒤에 요소를 추가 또는 이동한다.
문법
h1
요소 뒤에<p>World</p>
를 추가한다.
$( '<p>World</p>' ).insertAfter( 'h1' );
h1
요소 뒤로p
요소를 이동한다.
$( 'p' ).insertAfter( 'h1' );
예제 1
h1
요소 뒤에<p>World</p>
를 추가한다.
<!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>jQuery</title> <style> body { font-family: Consolas, monospace; font-size: 16px; } </style> <script src="//code.jquery.com/jquery-3.7.1.js"></script> <script> $( document ).ready( function() { $( '<p>World</p>' ).insertAfter( 'h1' ); } ); </script> </head> <body> <h1>Hello</h1> </body> </html>
예제 2
h1
요소 뒤로p
요소를 이동한다.
<!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>jQuery</title> <style> body { font-family: Consolas, monospace; font-size: 16px; } </style> <script src="//code.jquery.com/jquery-3.7.1.js"></script> <script> $( document ).ready( function() { $( 'p' ).insertAfter( 'h1' ); } ); </script> </head> <body> <p>World</p> <h1>Hello</h1> </body> </html>
참고
- A.after( B ) : A 뒤에 B 추가
- A.insertAfter( B ) : B 뒤에 A 추가
- A.before( B ) : A 앞에 B 추가
- A.insertBefore( B ) : B 앞에 A 추가