본문 바로가기

프로그래밍 공부/JavaScript

JavaScript - 문서 객체 생성

html 태그 안에 body 태그에 내용이 없다면 아무것도 출력되지 않는다. 하지만 script를 이용해서 body 태그에 동적으로 문서 객체를 넣을 수 있다. 문서 객체를 생성하려면 요소 노드(Element Node)와 텍스트 노드(Text Node)를 생성하고 텍스트 노드를 요소 노드에 연결 시켜야 한다.

메서드 이름 설명
document.createElement(tagName) 요소 노드를 생성한다.
document.createTextNode(text) 텍스트 노드를 생성한다.
1
2
3
4
window.onload=function(){
    let header = document.createElement('h1');
    let textNode = document.createTextNode('Document Object Model');
};
cs

위의 코드는 document.createElement() 메서드를 이용해 요소 노드인 h1태그를 만들었고, document.createTextNode() 메서드를 이용해 텍스트 노드를 만들었다. 다만 위의 코드를 실행하면 웹 페이지에 출력이 되지 않는다. 이유는 노드가 만들어 졌을뿐 아직 body 태그에 연결이 되지 않았기 때문이다.

메서드 이름 설명
appendChild(node) 객체에 노드를 연결한다.
1
2
3
4
5
6
7
window.onload=function(){
    let header = document.createElement('h1');
    let textNode = document.createTextNode('Document Object Model');
 
    header.appendChild(textNode);
    document.body.appendChild(header);
};
cs

appendChild()를 이용해 요소 노드인 header와 텍스트 노드인 textNode를 먼저 연결하고, 연결된 header를 다시 body 태그에 appendChild()를 이용해 연결을 해준 형태이다.

텍스트 노드를 가지지 않는 요소 노드에 경우 img 태그를 예로 들면 아래와 같이 작성한다.

1
2
3
4
5
6
7
8
window.onload=function(){
    let img = document.createElement('img');
    img.src="http://placehold.it/300x300";
    img.width=500;
    img.height=500;
 
    document.body.appendChild(img);
};
cs

img 변수를 선언후 document.createElement() 메서드를 이용해서 img 태그를 만들고 아래에 img.src 등을 이용해서 삽입할 이미지의 경로와 이미지의 크기등의 속성을 넣어 조작할 수 있다. 위의 방법은 웹 표준에서 정의하거나 웹 브라우저가 지원하는 태그의 속성에만 사용할 수 있다. 

예로 SVG(Scalable Vector Graphics) 태그에 경우 웹 브라우저에서 지원을 하지 않아 위의 방법을 사용할 수 없다. 웹 브라우저가 지원하지 않는 속성은 아래의 메서드를 통해 속성을 넣을 수 있다.

메서드 이름 설명
setAttribute(name, value) 객체의 속성을 지정한다.
getAttribute(name) 객체의 속성을 가져온다.
1
2
3
4
5
6
7
8
9
10
window.onload=function(){
    let img = document.createElement('img');
    img.setAttribute('src''http://placehold.it/300x300');
    img.setAttribute('width'500);
    img.setAttribute('height'500);
 
    img.setAttribute('data-property'300);
 
    document.body.appendChild(img);
}
cs

이전에 사용하는 방식으로는 data-property 속성을 넣을 수 없다. 따라서 data-property 속성을 넣으려면 setAttribute() 메서드를 이용해야한다.

이 외에도 innerHTML 속성을 사용하는 방법이 있다.

<h1> Document Object Model </h1>
빨강색 : 여는 태그
초록색 : innerHTML 속성
파란색 : 닫는 태그

innerHTML 속성은 태그의 내부를 의미하는 속성이다.

1
2
3
4
5
window.onload = function(){
    let output = '';
 
    document.body.innerHTML = output;
};
cs

위가 innerHTML 속성의 기본 형태이고 문자열을 선언하고 body 문서 객체의 innerHTML 속성에 넣기만 하면 문서 객체를 생성해준다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
window.onload = function(){
    let output = '';
    output += '<ul>';
    output += '     <li>JavaScript</li>';
    output += '     <li>jQuery</li>';
    output += '     <li>Ajax</li>';
    output += '</ul>';
 
    document.body.innerHTML = output;
 
    // 문서 객체에 내용을 추가하고 싶다면 innerHTML 속성에 
    // 복합대입 연산자로 문자열을 추가한다.
    document.body.innerHTML += '<h1>Document Object Model</h1>';
};
cs

인터넷 익스프롤러를 제외한 웹 브라우저는 모든 문서 객체의 innerHTML 속성을 바꿀 수 있다, 하지만 인터넷 익스프롤러는 col, colgroup, frameset, head, html, style, table, tbody, tfoot, thead, title 그리고 tr 태그의 innerHTML 속성을 바꿀 수 없다.

만약 문자열 <h1>Document Object Model</h1>을 화면에 그대로 출력하고 싶다면 text Content 속성을 사용하는 방법이 있다.

1
2
3
4
5
6
7
8
9
10
11
12
window.onload = function(){
    let output = '';
    output += '<ul>';
    output += '     <li>JavaScript</li>';
    output += '     <li>jQuery</li>';
    output += '     <li>Ajax</li>';
    output += '</ul>';
 
    document.body.textContent = output;
 
    document.body.textContent += '<h1>Document Object Model</h1>';
};
cs

textContent 속성을 사용하면 위와 같은 결과를 얻을 수 있다.

문서 객체 생성.html
0.00MB