새소식

반응형
WEB/jQuery

[jQuery] 제이쿼리 append 와 after 차이 알아보기

  • -
반응형

2021-03-31


Photo by Mathilde Langevin on Unsplash

기존의 HTML 문서의 추가적인 태그 및 데이터를 삽입하고자 할 때 append와 after를 고민하고는 하는데 오늘은 이 둘의 차이를 알아보자


- append 와 after의 정의

 

* append : 선택한 요소의 끝에 콘텐츠를 삽입합니다.

 

* after : 선택한 요소 뒤에 콘텐츠를 삽입합니다.

 

해당 메소드들의 정의를 읽어 보았을 때는 큰 차이가 없어 보이지만, 실제로 동작하는 방식은 크게 차이가 난다. 해당 두 메서드의 차이를 아래의 예제를 통해 알아보도록 하자.


- 예제

 

아래의 예제는 두개의 div를 출력하는 태그이다.

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">

#div1{
	width:300px;
	height: 200px;
	background: gray;

}

#div2{
	width:300px;
	height: 200px;
	background: tomato;
}


</style>


</head>
<body>
<div id="div1">div1</div>
<div id="div2">div2</div>

</body>
</html>​

 

해당 예제를 통해 div1 에는 append 메서드를 div2에는 after를 이용해서 html 태그를 추가해 보도록 하자.

 


- 결과

 

div1 / div2 각각 span 태그를 append 와 after를 통해 추가해 보았다. 

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>

<script src="https://code.jquery.com/jquery-2.2.4.min.js" ></script>
<script type="text/javascript">
$(document).ready(function(){
	
 	$("#div1").append("<span>Append</span>")
	$("#div2").after("<span>After</span>") 
})


</script>

<style type="text/css">

#div1{
	width:300px;
	height: 200px;
	background: gray;

}

#div2{
	width:300px;
	height: 200px;
	background: tomato;
}


</style>


</head>
<body>
<div id="div1">div1</div>
<div id="div2">div2</div>

</body>
</html>​

 

결과는 아래와 같이 상이한 결과가 나오게 된다. Append의 경우 div1 태그 안에 들어가 있으며, After의 경우 div2 밖에 위치하고 있다.

 

 

그렇다면 이러한 결과가 나오게 되는 이유는 무엇일까? 이유는 간단하다. append의 경우 추가된 html 태그를 자식 객체로 인식하여 자신에게 포함시키고, after의 경우 현재 div 태그를 벗어나 바로 다음 요소로써 html 태그를 추가시키기 때문이다.

 


메인 이미지 출처: Photo by Mathilde Langevin on Unsplash  

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.