본문 바로가기

프로그래밍/자바스크립트

[자바스크립트]DOM : innerHTML, 문서 객체의 스타일 처리

1. 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
25
26
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>문서 객체의 innerHTML 속성 사용</title>
<script type="text/javascript">
window.onload=function(){
        //변수 선언
        var output = '';
        output += '<ul>';
        output += '<li>Java</li>';
        output += '<li>Oracle</li>';
        output += '<li>HTML</li>';
        output += '<li>JavaScript</li>';
        output+='</ul>';
        
        document.body.innerHTML = output;    //HTML태그 허용
        
        //document.body.textContent = output;    //HTML태그를 허용하지 않고 텍스트로만 처리
        //<ul><li>Java</li><li>Oracle</li><li>HTML</li><li>JavaScript</li></ul>
};
</script>
</head>
<body>
</body>
</html>
cs

 

2. 문서 객체의 스타일 처리

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>문서 객체의 스타일 처리</title>
<script type="text/javascript">
window.onload = function(){
    //문서 객체 읽기(id가 header인 태그)
    var header = document.getElementById('header');
    
    //문서 객체의 스타일 처리
    header.style.border = '2px solid black';
    header.style.color = 'orange';
    header.style.fontFamily = 'Helvetica';    //자바스크립트는 식별자에 하이픈을 못쓰므로 font-family가 아니라 fontFamily로 지정
    header.style.backgroundColor = 'yellow';//background-color -> backgroundColor
};
</script>
</head>
<body>
    <h1 id="header">Header</h1>
</body>
</html>
cs