본문 바로가기

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

[자바스크립트] DOM : getElementsByTagName(), getElementById(), getElementsByName(), getElementsByClassName()

1. DOM(문서 객체 모델)

- 넓은 의미로 웹 브라우저가 HTML페이지를 인식하는 방법

- 좁은 의미로는 document객체와 관련된 객체 집합

- 사용시 HTML페이지에 태그를 추가, 수정, 제거 할 수 있다.

- 문서객체 : 태그를 자바스크립트에서 이용할 수 있는 객체로 만든것

 

2. getElementsByTagName()

- 태그명을 통해서 태그를 탐색해서 문서객체로 반환
- 복수의 태그가 존재할 수 있기 때문에 배열로 반환

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>태그명을 통해서 문서 객체 탐색</title>
<script type="text/javascript">
window.onload=function(){
    var spans = document.getElementsByTagName('span');
    spans[0].innerHTML = '달빛이 찬란한 호수';
    spans[1].innerHTML = '흰눈이 눈부신 들판';
};
</script>
</head>
<body>
    <span>하늘</span><br>
    <span>하늘</span>
</body>
//출력결과
달빛이 찬란한 호수
흰눈이 눈부신 들판
</html>
cs
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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>태그명을 통해서 문서 객체 탐색</title>
<script type="text/javascript">
    window.onload=function(){
        var spans = document.getElementsByTagName('span');
        
        for(var i =0; i<spans.length;i++){
            if(i%2==1){    //홀수이면
                spans[i].innerHTML = '우주';
            }else{        //짝수이면
                spans[i].innerHTML = '지구'
            }
        }
    }
</script>
</head>
<body>
    <span>바다</span><br>
    <span>바다</span><br>
    <span>바다</span>
</body>
//출력결과
지구
우주
지구
</html>
cs

 

3. getElementById()

- 태그의 id를 통해 문서 객체 탐색

- id는 중복될 수 없으므로 배열로 접근하지 않는다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>id를 통해서 문서객체 탐색</title>
<script type="text/javascript">
    window.onload = function(){
        //id를 통해 문서 객체 탐색
        var header1 = document.getElementById('header_1');
        var header2 = document.getElementById('header_2');
        
        header1.innerHTML='헤더1입니다';
        header2.innerHTML='헤더2입니다';
    }
</script>
</head>
<body>
    <h1 id = "header_1">Header</h1>
    <h1 id = "header_2">Header</h1>
</body>
//출력결과
헤더1입니다
헤더2
</html>
cs

 

4. getElementsByName()

- 태그의 name을 통해 문서 객체 탐색

- 태그의 name은 중복될 수 있으므로 배열로 접근

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
30
31
32
33
34
35
36
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>name 속성을 이용한 문서 객체 탐색</title>
<script type="text/javascript">
window.onload=function(){
    /*name은 중복가능하므로 배열로 접근*/
    var prev = document.getElementsByName('prev');
    var next = document.getElementsByName('next');
    
    prev[0].innerHTML = '이전';
    next[0].innerHTML = '다음';
    
    var country = document.getElementsByName('country');
    country[0].checked = true;
    
    var comment = document.getElementsByName('comment');
    comment[0].value = '간단한 설명 입력';
};
</script>
</head>
<body>
 
    <button name="prev">prev</button>
    <br>
    <button name="next">next</button>
    <br>
        <!-- id는 유니크하지만 name은 중복가능하다. -->
    <input type = "checkbox" name="country" value="한국">한국
    <input type = "checkbox" name="country" value="미국">미국
    <input type = "checkbox" name="country" value="일본">일본
    <br>
    <input type="text" name="comment">
</body>
</html>
cs

 

5. getElementsByClassName()

- 클래스 명을 이용하여 문서 객체 탐색

- HTML5에서 지원해주지만, HTML5가 아니더라도 최신 브라우저에서는 클래스를 이용한 문서 객체 탐색을 지원

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
30
31
32
33
34
 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>클래스를 이용한 문서 객체 탐색</title>
<script type="text/javascript">
    window.onload = function(){
        //클래스명이 matched인 복수의 태그를 배열로 반환한다. 
        var foo = document.getElementsByClassName('matched');
        var output='';
        for(var i=0;i<foo.length;i++){
        //alert창에서 작동시키므로 <br>가 아닌 \n로 작성
            output += foo[i].innerHTML + '\n'
        }
        alert(output); //A,B,D
    };
</script>
</head>
<body>
<p id="foo">
    <span class="matched">A</span>
    <span class="matched unmatched">B</span>
    <span class="unmached">C</span>
</p>
 
<p id="bar">
    <span class="matched">D</span>
</p>
//출력결과
A
B
D
</body>
</html>
cs
 
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
30
31
32
33
34
35
 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>클래스를 이용한 문서 객체 탐색</title>
<script type="text/javascript">
    window.onload = function(){
        //클래스의 속성 값이 matched인 복수의 태그를 배열로 반환한다. 
        var foo2 = document.getElementById('foo');
        
        //id가 foo인 p태그 하위태그에서 class 속성 값이 matched인 span태그 탐색 --> A,B
        var fooMatched = foo2.getElementsByClassName('matched');
        var output2 = '';
        for(var i=0; i<fooMatched.length;i++){
            output2+= fooMatched[i].innerHTML +'\n';
        }
        alert(output2);
    };
</script>
</head>
<body>
<p id="foo">
    <span class="matched">A</span>
    <span class="matched unmatched">B</span>
    <span class="unmached">C</span>
</p>
 
<p id="bar">
    <span class="matched">D</span>
</p>
//출력결과
A
B
</body>
</html>
cs

 

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
30
31
32
33
 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>클래스를 이용한 문서 객체 탐색</title>
<script type="text/javascript">
    window.onload = function(){
        //클래스명이 여러개인 경우 공백을 구분자로 해서 문자열로 전달 가능.
        //순서는 같지 않아도 됨(이 경우, 'unmatched matched'도 가능)
        //matched도 적용되어있고, unmatched도 적용되어있는 태그를 찾아라. -> B
        var fooMatched2 = document.getElementsByClassName('matched unmatched');    
        var output3 = '';
        for(var i =0; i<fooMatched2.length;i++){
            output3 += fooMatched2[i].innerHTML+'\n';
        }
        alert(output3);
    };
</script>
</head>
<body>
<p id="foo">
    <span class="matched">A</span>
    <span class="matched unmatched">B</span>
    <span class="unmached">C</span>
</p>
 
<p id="bar">
    <span class="matched">D</span>
</p>
//출력결과
B
</body>
</html>
cs