티스토리 뷰

 [javascript 14강] DOM (문서 객체)



이번글에서는 DOM 객체에 대해서 알아보겠습니다.

javascript DOM 객체는 Document Object Model 의 약자로 HTML 태그와 관련된 객체입니다.

DOM 객체는 다이나믹 문서 제작, 서버접속, 게임제작 등 다양한 기능을 위해 많이 사용되고 있습니다.

DOM 객체에서.. 웹에 필요한 기능들을 주로 살펴보도록 하겠습니다.

문서만들기, 객체선택 및 삭제, css 작성 및 수정 등에 대해서 자세히 알아보도록하겠습니다.


 이전 글 링크 



 DOM 객체에 들어가기전... 기본지식


DOM 객체에 들어가기전.. HTML 문서에 대해서 기본적으로 알아야할 단어들이있습니다.

바로 태그, 노드, 객체 입니다.


태그는 <head>, <body>, <div>, <p>... 등등등 HTML 안에서 사용할수 있는 것들의 하나의 단위입니다.


노드는 트리형테의 요소들이라고 생각하시면됩니다. 

예를 들어 <body> 태그안에 <div> 태그가있고.. 그안에<a> 태그가 있다고하면..

body 의 노드는 body, div, a 태그가 되는것 입니다.


객체는 태그의 하나하나의 요소들이 모두 포함되어 있는것을 객체라고 합니다.


설명의 내용에 추가 이미지를 그려보았습니다..

 설명이미지 



 javaScript 를 이용해서 문서만들기 (텍스트) (createElement, createTextNode)


html 영역에 태그를 작성하지 않고 javascript 로 태그를 추가하여 문서를 작성할수 있습니다.

즉 동적으로 태그를 추가하는것 입니다.


 사용방법 및 문법 


1. 태그 객체 생성


var 변수 = document.createElement("생성할 태그");


2. 태그 객체 텍스트 생성


var 변수 = document.createTextNode("문자");


3. 태그 객체 추가


태그객체.appendChild(태그객체);


document.body.appendChild(태그객체);

(document : 문서전체, body: 바디영역)



 예제 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
        <script type="text/javascript">
            window.onload = function(){
                var node = document.createElement("h1");
                var textNode = document.createTextNode("h1 태그의 택스트");
                
                node.appendChild(textNode);
                document.body.appendChild(node);
            }
        </script>
    </head>
    <body>
        
    </body>
</html>
cs


 실행결과 및 설명 

 


위의 이미지는 출력결과입니다.

<body> 역영에는 아무것도 없지만 자바스크립트를통해 h1 태그 및 텍스트를 추가하여 출력된것을 확인할수 있습니다.


var node = document.createElement("h1"); 

변수 node 에 h1 태그 객체를 생성해 주었습니다.


var textNode = document.createTextNode("h1 태그의 택스트");

변수 testNode 에 "h1" 태그의 택스트" 라고 택스트 객체를 생성하였습니다.


node.appendChild(textNode);

위에서 생성한 h1 태그객체인 node 요소에 appendChild 사용하여 textNode 를 하위노드에 추가하였습니다.


document.body.appendChild(node); 

다음 최상위 document 로 접근하고 다음 노드인 body 로 접근하여 appendChild 사용하여 node 객체를 하위노드에 추가하였습니다.


그결과 위와같은 이미지의 결과를 확인할수 있습니다.




 javaScript 를 이용해서 문서만들기 (이미지) (createElement, createTextNode, setAttribute)


위에서 javascript 를 통해 text 를 추가해보았습니다.

이번에는 javascript 를 통해 이미지를 추가해보도록 하겠습니다.


 사용방법 및 문법 


1. 태그 객체 생성


var 변수 = document.createElement("생성할 태그");


2. 태그 속성 추가


태그변수.src = "이미지주소";

태그변수.width = "넓이";

태그변수.height = "높이";


3. 태그 속성 함수로 추가


태그변수.setAttribute("속성","값");



 예제 

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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
        <script type="text/javascript">
            window.onload = function(){
                var imgNode = document.createElement("img");
                imgNode.src = "./img/googleLogo.PNG";
                imgNode.width = "50";
                imgNode.height = "50";
                document.body.appendChild(imgNode);
                
                var imgNode2 = document.createElement("img");
                imgNode2.setAttribute("src","./img/googleLogo.PNG");
                imgNode2.setAttribute("width","50");
                imgNode2.setAttribute("height","50");
                
                document.body.appendChild(imgNode2);
                
            }
        </script>
    </head>
    <body>
        
    </body>
</html>
cs


 실행결과 및 설명 

 


결과로는 로고가 2개가 출력됩니다.


               var imgNode = document.createElement("img");
                imgNode.src = "./img/googleLogo.PNG";
                imgNode.width = "50";
                imgNode.height = "50";
                document.body.appendChild(imgNode);

img 변수에 img 태그 객체를 생성해 줍니다.

그다음 속성으로 src, width, height 를 넣어주고

document.body 영역에 appendChild 를 사용하여 imgNode 를 하위요소에 추가합니다.



               var imgNode2 = document.createElement("img");
                imgNode2.setAttribute("src","./img/googleLogo.PNG");
                imgNode2.setAttribute("width","50");
                imgNode2.setAttribute("height","50");
                
                document.body.appendChild(imgNode2);

img 변수에 img 태그 객체를 생성해 줍니다.

그다음 setAttribute 함수를 통해 src, width, height 를 넣어주고

document.body 영역에 appendChild 를 사용하여 imgNode 를 하위요소에 추가합니다.


그결과 위와같이 구글로고가 2개가 출력이됩니다.




 텍스트변수를 이용하여 태그추가 (innerHTML)


위에서 객체를 통해 속성이나 함수로 값을 정해주고

appendChild 함수로 태그를 추가하였습니다.

이번 innerHTML 속성을 사용하여 텍스트형식을 그대로 추가하는 방법에 대해서 알아보겠습니다.


 사용방법 및 문법 


document.body.innerHTML = 문자변수;



 예제 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
        <script type="text/javascript">
            window.onload = function(){
                
                var str = "";
                str += "<div>";
                str += "<img src='./img/googleLogo.PNG' width='50' height='50'>";
                str += "</div>";
                
                document.body.innerHTML = str;
                
            }
        </script>
    </head>
    <body>
        
    </body>
</html>
cs


 실행결과 및 설명 

 


결과로 구글로고가 나오는것을 확인할수 있습니다.


               var str = "";
                str += "<div>";
                str += "<img src='./img/googleLogo.PNG' width='50' height='50'>";
                str += "</div>";

str 변수에 택스트로 HTML 요소들을 입력해줍니다.


document.body.innerHTML = str;

다음 document.body 영역으로 가서 innerHTML 이라는 속성에 str 값을 할당해 줍니다.


그럼 위와같은 이미지의 결과를 얻을수 있습니다.



 태그의 ID 속성값을 활용하여 객체선택 (getElementById)


이제 중요한 객체 선택입니다.

객체를 선택해야 추가,삭제,수정 이 가능하기에 가장중요하다고 생각합니다.

그리고 실무에서도 많이 쓰입니다.


 사용방법 및 문법 


var 변수 = document.getElementById("id속성값");



 예제 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
        <script type="text/javascript">
            window.onload = function(){
                
                
                var logo = document.getElementById("logoImg");
                logo.setAttribute("width""200");    
                
            }
        </script>
    </head>
    <body>
        <div>
            <img id="logoImg" src='./img/googleLogo.PNG' width='50' height='50'>
        </div>
    </body>
</html>
cs


 실행결과 및 설명 

 


위의 실행결과로 로고의 넓이가 커진것을 확인할수 있습니다.


<img id="logoImg" src='./img/googleLogo.PNG' width='50' height='50'>

id 가 "logoImg" 라는 <img> 태그를 미리 만들어두었고 크기를 50X50 사이즈로 만들었습니다.


           window.onload = function(){
                
                
                var logo = document.getElementById("logoImg");
                logo.setAttribute("width""200");    
                
            }

그다음 onload 를 사용하여 모두 로드가 끝난뒤..

var logo = document.getElementById("logoImg");

getElementById 를 사용하여 logo 변수에 <img> 태그의 객체를 넣어주었습니다.

그럼 logo 라는 변수에는 <img id="logoImg" src='./img/googleLogo.PNG' width='50' height='50'> 라는 내용이 객체로 들어가있습니다.

그다음 setAttribute 를 사용하여 넓이를 200으로 고쳐주었고


그결과 위와같은 이미지의 결과를 확인할수 있습니다.




 자식객체 삭제 (removeChild)


위에서는 객체를 추가하는 방법에대해서 알아보았습니다.

그럼 하위객체 즉 자식객체를 삭제하기위한 방법에대해서 알아보겠습니다.


 사용방법 및 문법 


객체변수.parentNode.removeChild(객체변수);



 예제 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
        <script type="text/javascript">
            window.onload = function(){
                
                var imgNode = document.getElementById("logoImg");
                imgNode.parentNode.removeChild(imgNode);
                
            }
        </script>
    </head>
    <body>
        <div>
            <img id="logoImg" src='./img/googleLogo.PNG' width='50' height='50'>
        </div>
    </body>
</html>
cs


 실행결과 및 설명 

 


우선 결과부터 살펴본다면 아무것도 나오지 않습니다.


<img id="logoImg" src='./img/googleLogo.PNG' width='50' height='50'>

img 태그를 미리 생성해두었습니다.


           window.onload = function(){
                
                var imgNode = document.getElementById("logoImg");
                imgNode.parentNode.removeChild(imgNode);
                
            }

다음 onload 를 사용하여 모두 로딩된후에..

var imgNode = document.getElementById("logoImg");

imgNode 변수에 id 값이 "logoImg" 라는 태그의 객체를 할당해주었습니다.

imgNode.parentNode.removeChild(imgNode);

만들어둔 imgNode 변수의 부모로 이동하기위해 parentNode 속성을 사용하고

그다음 removeChild 함수를 사용하여 imgNode 객체를 지워주었습니다.


그결과 위의 이미지의 결과를 얻을수 있습니다.




 style 속성 변경 (style)


이번에는 객체선택후 style 을 변경할수있는 style 속성에 대해서 알아보겠습니다.


 사용방법 및 문법 


객체변수.style.스타일속성 = "값";



 예제 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
        <script type="text/javascript">
            window.onload = function(){
                
                var imgNode = document.getElementById("logoImg");
                imgNode.style.width = "300px";
                imgNode.style.height = "100px";
                
            }
        </script>
    </head>
    <body>
        <div>
            <img id="logoImg" src='./img/googleLogo.PNG' width='50' height='50'>
        </div>
    </body>
</html>
cs


 실행결과 및 설명 

 


결과를 보면 300X100 의 로고가 출력되는것을 확인할수 있습니다.


<img id="logoImg" src='./img/googleLogo.PNG' width='50' height='50'>

img 태그를 미리 생성해두었습니다.


           window.onload = function(){
                
                var imgNode = document.getElementById("logoImg");
                imgNode.style.width = "300px";
                imgNode.style.height = "100px";
                
            }

다음 onload 를통해 로딩이 완료된후에..

var imgNode = document.getElementById("logoImg"); 

변수 imgNode 에 아이디가 "logoImg" 인 태그객체를 할당해 주었습니다.

               imgNode.style.width = "300px";
                imgNode.style.height = "100px";

다음 imgNode 의 style 속성으로 width, height 값을 300px, 100px 로 넣어주었습니다.


그결과 위와같은 이미지의 결과를 얻을수 있습니다.




 글을 마치며..


이번글을 통해 DOM 객체의 다양한 사용방법을 알아보았습니다.

DOM 객체는 BOM 객체보다 많이 사용됩니다.

그중에서도 객체 선택하는 방법을 꼭! 알아두시길 바랍니다.


도움이 되셨다면 로그인 없이 가능한

아래 하트♥공감 버튼을 꾹 눌러주세요! 




댓글