Javascript div 동적 생성 - Javascript div dongjeog saengseong

순수 자바스크립트  HTML 태그 요소 동적 추가 및 삭제

자바스크립트 HTML 태그 요소 동적 추가 및 삭제 방법은 DOM 객체를 생성하여 DOM 트리에 동적 생성/삭제하려는 내용을 추가시키면 된다.

1 DOM 객체 생성

document.createElement("태그이름"); 를 호출하면 HTML 태그의 DOM 객체를 생성할 수 있다.  
이제 newDIV 객체의 프로퍼티를 이용하여 <div> 태그를 완성할수 있다

 var newDIV = document.createElement("div");​

2 innerHTML 프로퍼티를 이용

innerHTML 프로퍼티를 이용하여  <div> 태그에 HTML 텍스트를 삽입

newDIV.innerHTML = "새로 생성된 DIV입니다.";

<div> 태그에 속성을 추가하거나 CSS스타일 시트도 달 수 있다.

newDIV.setAttribute("id","myDiv");

newDIV.style.backgroundColor="yellow";

중간과정확인 : DOM 객체 확인

<div id="myDiv"
    style="background-color:yellow">
    새로 생성된 DIV입니다.
</div>

3 DOM 트리에 삽입

이제 이 newDIV 객체를 DOM 트리에 삽입해보자.
DOM 객체를 DOM 트리에 삽입할 때 대표적으로 다음 2가지 방법을 활용한다.

부모.appendChild(DOM객체); // DOM 객체를 부모의 마지막 자식으로 삽입

부모.insertBefore(DOM객체,기준자식); // DOM 객체를 부모의 자식 객체 중 기준자식 앞에 삽입

다음은 앞에서 만든 newDiv 객체를 <p "id=p"> 태그의 마지막 자식으로 추가하는 자바스크립트 코드이다.
코드에 의해 newDIV가 삽입되면 DOM 트리가 바뀌고 브라우저 화면이 바로 갱신된다.

var p = document.getElementById("p"); // <p "id=p"> 태그의 DOM 객체 찾기
p.appendChild(newDiv);

4 DOM 객체의 삭제

removeChild() 메소드를 이용하면 부모에게서 자식 객체를 떼어낼 수 있다.

var removedObj = 부모.removeChild(떼어내고자하는자식객체);

"id=myDiv"인 DOM 객체를 DOM 트리에서 떼어내고자 하면 다음과 같이 한다

var myDiv = document.getElementById("myDiv");
var parent = myDiv.parentElement; // 부모 객체 알아내기
parent.removeChild(myDiv); // 부모로부터 myDiv 객체 떼어내기

DOM 객체가 DOM 트리에서 제거되면 브라우저 화면이 즞각 갱신되어 DOM 객체에 의해 출력된 HTML 콘텐츠가 사라진다. 떼어낸 myDiv 객체는 DOM 트리의 임의의 위치에 다시 부착할수 있다.

<!DOCTYPE html>

<html>

<head>

<title>자바스크립트 객체 지우기 테스트</title>

<meta charset="utf-8">

<script>

function deleteDIV(  deletingDivObj  )

{

var parentObj = deletingDivObj.parentNode ;

parentObj.removeChild( deletingDivObj );

};

window.onload = function () {

var colorCode  = "#ffffff";

var bodyObj = document.getElementById("body");

for( i = 0 ; i<= 100 ; i++){

RcolorCode  = "#" + Math.round(Math.random() * 0xffffff).toString(16) ;

var newDIV = document.createElement("div");

newDIV.innerHTML = "새로 생성된 DIV"+i+" 입니다.";

newDIV.setAttribute("id","DIV"+i);

newDIV.style.backgroundColor= RcolorCode;

newDIV.onclick = function()

{

deleteDIV( this );

}

bodyObj.appendChild(newDIV);

}

};

</script>

</head>

<body id="body" >  

</body>

</html>

/* =========================== */

[ 개발 환경 설정 ]

개발 툴 : Edit++

개발 언어 : javascript

Javascript div 동적 생성 - Javascript div dongjeog saengseong

/* =========================== */

/* =========================== */

[소스 코드]

    <script>

    	/*
    	[JS 요약 설명]
    	1. document.createElement : 특정 태그를 생성합니다
    	2. setAttribute : 특정 태그 속성값을 지정합니다
    	3. appendChild : 어느 부모에 추가할지를 결정합니다    	
    	*/

    	/* 동적 레이아웃 추가 함수 */
    	function addLayOut(){
    		console.log("addLayOut : debug [1]");


    		/* 행 : div 레이아웃 생성 및 스타일 지정 */
    		var createMainDiv = document.createElement("div");
    		createMainDiv.setAttribute("id", "childMainDiv");
    		var createMainDivStyle = "width:96%; height:10%; margin:1% auto; padding:0; border:none;";
    		createMainDivStyle = createMainDivStyle + "float:top; position:relative; top:0%; left:0%;";
    		createMainDiv.setAttribute("style", createMainDivStyle);
    		//createDiv.setAttribute("onclick", "ButtonClick(this)");
    		console.log("addLayOut : debug [2]");


    		/* 생성한 div에 추가 컴포넌트 붙임 작업 */
    		var createSecondOneDiv = document.createElement("div");
    		createSecondOneDiv.setAttribute("id", "childSecondOneDiv");
    		var createSecondOneDivStyle = "width:5%; height:100%; margin:0 auto; padding:0; border:none; background-color:#ff00ff;";
    		createSecondOneDivStyle = createSecondOneDivStyle + "float:left; position:relative; top:0%; left:0%;";
    		createSecondOneDiv.setAttribute("style", createSecondOneDivStyle);
    		//createSecondOneDiv.setAttribute("onclick", "ButtonClick(this)");
    		createMainDiv.appendChild(createSecondOneDiv); //[createMainDiv] 쪽에 붙임
    		console.log("addLayOut : debug [3]");


    		/* 생성한 div에 추가 컴포넌트 붙임 작업 */
    		var createSecondTwoDiv = document.createElement("div");
    		createSecondTwoDiv.setAttribute("id", "childSecondTwoDiv");
    		var createSecondTwoDivStyle = "width:90%; height:100%; margin:0 auto; padding:0; border:none; background-color:#ff0000;";
    		createSecondTwoDivStyle = createSecondTwoDivStyle + "float:left; position:relative; top:0%; left:0%; display:table;";
    		createSecondTwoDiv.setAttribute("style", createSecondTwoDivStyle);
    		//createSecondTwoDiv.setAttribute("onclick", "ButtonClick(this)");
    		createMainDiv.appendChild(createSecondTwoDiv); //[createMainDiv] 쪽에 붙임
    		console.log("addLayOut : debug [4]");


    		/* 생성한 div에 추가 컴포넌트 붙임 작업 */
    		var createSecondTwoDivTxt = document.createElement("p");
    		createSecondTwoDivTxt.innerText = "hello"; //텍스트 삽입			
    		createSecondTwoDivTxt.setAttribute("id", "childSecondTwoDivTxt");
    		var createSecondTwoDivTxtStyle = "text-align:center; color:#ffffff; font-weight:bold; font-size:100%;";
    		createSecondTwoDivTxtStyle = createSecondTwoDivTxtStyle + "display:table-cell; vertical-align : middle;";
    		createSecondTwoDivTxt.setAttribute("style", createSecondTwoDivTxtStyle);			
    		createSecondTwoDiv.appendChild(createSecondTwoDivTxt); //[createSecondTwoDiv] 쪽에 붙임
    		console.log("addLayOut : debug [5]");


    		/* 최종 지정한 부모쪽에 붙여 넣음 */
    		var parentDiv = document.getElementById("main_container");
    		parentDiv.appendChild(createMainDiv);
    		console.log("addLayOut : debug [6]");
    	}

    </script>

/* =========================== */

/* =========================== */

[결과 출력]

Javascript div 동적 생성 - Javascript div dongjeog saengseong

/* =========================== */

/* =========================== */

[요약 설명]

/*

[JS 요약 설명]

1. document.createElement : 특정 태그를 생성합니다

2. setAttribute : 특정 태그 속성값을 지정합니다

3. appendChild : 어느 부모에 추가할지를 결정합니다

*/

/* =========================== */