- DOM 객체 찾기, document.getElementByld()

DOM 트리에서 특정 DOM 객체를 찾아내는 방법을 알아보자. 가장 간단한 방법은 id 속성 값을 매개 변수로 document 객체의 getElementById() 메소드로 호출하면 된다.


document.getElementById(idVal)

idVal : 찾고자 하는 객체의 id 속성 값, 문자열

(DOM 트리에서 id 속성값이 idVal인 DOM 객체를 찾아 리턴한다. idval 값을 가진 객체가 없다면, null을 리턴한다.

같은 값을 가진 객체가 여러 개 있다면 HTML 페이지에 먼저 등장하는 객체를 리턴한다.)


ex)

var p = document.getElementById("firstP"); // id 속성 값이 firstP인 DOM 객체 p 리턴

p.style.color = "red"; // p 객체의 글자 색을 red로 변경


document.getElementById("firstP").style.color = "red"; // 위 코드를 한줄로 작성하기


* HTML 문서 전체를 대표하는 객체가 document이고 DOM 트리의 루트이다.


- DOM 객체의 CSS3 스타일 동적 변경

style 객체는 HTML 태그의 CSS3 스타일 시트 정보로만 가진 객체로서, DOM 객체의 style 프로퍼티로 접근한다.

style 객체를 이용하면 이미 출력된 HTML 태그의 모양을 변경할 수 있다.


ex)

첫번째 방법 

obj.style.backgroundColor = "green"; // DOM 객체 obj의 배경을 green 색으로 설정


두번째 방법

obj.style.cssText = "background-color : green" // style 객체의 cssText 프로퍼티에 CSS3 스타일 시트를 직접 주는 방법


- DOM 객체의 CSS3 스타일 프로퍼티 읽기


HTML 태그 안에 지정된 인라인 CSS3 스타일의 경우

<span id ="mySpan" style="color:red">문장입니다.</span>


var span = document.getElementById("mySpan");

var color = span.style.color; // color = "red"


하지만, 셀렉터를 이용하여 CSS3 스타일이 지정된 경우, 앞의 방식으로 CSS3 프로퍼티 값을 읽을수 없다.

DOM 객체의 CSS3 스타일 프로퍼티 값을 읽는 전형적이고 확실한 방법은 다음과 같다.


var span = document.getElementById("myspan");

var style = window.getComputedStyle(span); // span 객체의 CSS3 스타일 객체

var value = stylle.getPropertyValue("color"); // value는 color 프로퍼티의 값 "red"







예제 8-2. 자바스크립트로 <span>태그의 CSS3 스타일 동적 변경

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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CSS 스타일 동적 변경</title>
<script>
function change() {
    var span = document.getElementById("mySpan"); // id가 mySpan인 객체 찾기
    span.style.color = "green"// 글자 색 green
    span.style.fontSize = "30px"// 글자 크기는 30픽셀
    span.style.display = "block"// 블록 박스로 변경
    span.style.width = "6em"// 박스의 폭. 6 글자 크기
    span.style.border = "3px dotted magenta"// 3픽셀 점선 magenta 테두리
    span.style.margin = "20px"// 상하좌우 여백 20px
}
</script>
</head>
<body>
<h3>CSS 스타일 동적 변경</h3>
<hr>
<p style="color:blue" >이것은
    <span id="mySpan" style="color:red">문장입니다.    </span>
</p>
<input type="button" value="스타일변경" onclick="change()">
</body>
</html>
 
cs





Posted by 너래쟁이
: