HTML 문서에서 특정 대상을 구분하는 용도로 사용되는 속성
id, class, 태그 등을 사용
document 객체를 사용하여 특정 선택자를 갖는 요소를 선택하는 방법
id 선택자 : document.getElementById("id선택자명");
class 선택자 : document.getElementByClassName("class선택자명");
태그 선택자 : document.getElementByTagName("태그선택자명")
-> 리턴되는 객체를 통해 해당 요소에 접근하여 다양한 작업 수행 가능
<script>
function func() {
let header1 = document.getElementById("header1");
// 변수 선언을 통해 header1 저장
alert(header1);
// alert() 함수로 출력하면
// [object HTMLHeadingElement] 객체가 출력되기 때문에
// 지정된 객체에 접근하여 속성변경이 가능해짐
header1.style.background = "YELLOW";
// style 속성을 이용해 배경색을 노란색으로 변경
document.getElementById("header2").style.background = "SKYBLUE";
// 변수에 저장하지 않고 바로 사용도 가능
let header5 = document.getElementByClassName("header5");
// 변수 선언을 통해 header5 클래스 저장
for(let h5 of header5) {
h5.style.background = "GREEN";
}
// 복수 개의 객체이기 때문에 for문을 이용해서 출력해야 함
let tag = getElementByTagName("h2");
// 변수 선언을 통해 h2 태그를 모두 저장
for(let h2 of tag) {
h2.style.background = "PINK";
}
// h2 태그를 두 번 써서 복수 개의 객체이므로 for문을 이용하여 출력해야 함
}
</script>
</head>
<body>
<input type="button" value="확인" onclick="func()">
<h3 id="header1">header1</h3>
<h3 id="header2">header2</h3>
<hr>
<h2 id="header3">header3</h2>
<h2 id="header4">header4</h2>
<hr>
<h3 class="header5">header5_1</h3>
<h3 class="header5">header5_2</h3>
</body>
대상 요소의 내용 확인 또는 변경 용도로 사용
innerText
: 대상 요소의 내용 중 텍스트만 취급
innerHTML
: 대상 요소의 내용을 HTML 태그까지 취급
< 기본 사용법 >
- 확인
document.getElementXXX.innerText
document.getElemnetXXX.innerHTML
- 변경
document.getElementXXX.innerText = "내용";
document.getElementXXX.innerHTML = "내용";
⭐ innerText
입력
<script>
function func1() {
let divAreaText = document.getElementById("divAreaText");
divAreaText.innerText = "<h3>innerText로 변경한 텍스트</h3>";
}
</script>
<body>
<button onclick="func1()">innerText</button>
<div id="divAreaText"><!--innerText로 내용 변경--></div>
</body>
📌 출력
⭐ innerHTML
입력
<script>
function func2() {
let divAreaHtml = document.getElementById("divAreaHtml");
divAreaHtml.innerText = "<h3>innerHTML로 변경한 텍스트</h3>";
}
</script>
<body>
<button onclick="func2()">innerHTML</button>
<div id="divAreaHtml"><!--innerHTML로 내용 변경--></div>
</body>
📌 출력
어떤 작업을 주기적으로 반복하기 위해서 setInterval()
함수를 호출하여 반복할 함수와 반복 주기를 파라미터로 전달
-> 반복 주기는 밀리초(ms) 단위의 값 전달(1초 = 1000밀리초)
< 기본 문법 >
setInterval(함수, 반복주기);
< 반복 중지 기본 문법 >
clearInterval(중지할 타이머 객체);