
:웹 문서(HTML)의 모든 요소를 객체 형식으로 표현하는 방법
-> 문서 내 특정 요소에 접근하는 방법을 제공
(1) id 속성 값으로 접근하기
: document.getElementById("id 속성값");
(2) class 속성 값으로 접근하기
: document.getElementsByClassName("class 속성값");
(3) name 속성 값으로 접근하기
: document.getElementsByName("name 속성값");
(4) tag name으로 접근하기
: document.getElementsByTagName("태그명");
(5) css 선택자를 이용해서 접근하기
<button onclick="fnTest1()">클릭할 때 마다 배경색 변경</button>
<div id="div1" class="area"></div>
//id로 접근하기
function fnTest1(){
//id가 "div1"인 요소를 얻어와 상수형 변수인 div1에 저장
const div1 = document.getElementById("div1");
//접근한 요소의 배경색을 얻어와 변수(bgColor)에 저장
cons bgColor = div1.style.backgroundColor;
//bgColor가 red이면 div1의 색을 yellow로 바꿔라
// 아니면(red가 아니면) red로 바꿔라
if(bgColor=='red'){
div1.style.backgroundColor = "yellow";
}else{
div1.style.backgroundColor = "red";
}
}
<div class="area div2"></div>
<div class="area div2"></div>
<div class="area dic2"></div>
<button onclick="fnTest2()">배경색 변경하기</button>
function fnTest2(){
const arr = document.getElementsByClassName("div2")
console.log(arr)
console.log(arr[0])
console.log(arr[1])
console.log(arr[2])
arr[0].style.backgroundColor="green";
arr[1].style.backgroundColor="yellow";
arr[2].style.backgroudnColor="red";
for(let i=0; i<arr.length; i++){
arr[i].innerText = i+'번째 요소입니다.';
}
}
<ul>
<li>20</li>
<li>80</li>
<li>140</li>
<li>200</li>
<li>255</li>
</ul>
<button onclick="fnTest3()">배경색 변경하기</button>
function fnTest3(){
//문서내에 존재하는 모든 li요소를 얻어와 배열 형식으로 반환하고 있음
const arr = document.getElementsByTagName("li");
for(i=0; i<arr.length; i++){
const num = arr[i].innerText;
arr[i].style.backgroundColor="rgb(100," + num + ", 130)";
}
}
<input type="text" id="inputText">
<button onclick="fnTest4()">입력</button>
function fnTest4(){
// input 요소에 접근
const input = doucument.getElementById("inputText");
// input관련 태그에 작성된 값을 나타내는 속성 == value
// input 요소에 작성된 값을 얻어와 alert로 출력
alert(input.value);
input.value="";
}
<table>
<tr>
<td>
<label>
<input type="checkbox" name="hobby" value="게임">게임
</label>
</td>
<td>
<label>
<input type="checkbox" name="hobby" value="음악감상">음악감상
</label>
</td>
<td>
<label>
<input type="checkbox" name="hobby" value="영화감상">영화감상
</label>
</td>
</tr>
<tr>
<td>
<label>
<input tyep="checkbox" name="hobby" value="운동">운동
</label>
</td>
<td>
<label>
<input type="checkbox" name="hobby" value="독서">독서
</label>
</td>
<td>
<label>
<input type="checkbox" name="habby" value="코딩">코딩
</label>
</td>
</tr>
</table>
<button onclick="fnTest5()">선택완료</button>
<div class="area" id="result5"></div>
function fnTest5(){
const hobbyArr = document.getElementsByName("hobby");
let str=""; //체크된 체크박스의 값을 누적할 변수 선언
let count="0; //체크 개수 카운드
for(let i=0; i<arr.hobbyArr.length; i++){
//.checked속성
//해당 요소가 체크되면 true / 아니면 false
//radio, checkbox 전용 속성
if(hobbyArr[i].checked){
str += hobbyArr[i].value + ""; //값 누적
count++; //1개씩 증가
}
cosnt result5 = document.getElementById("result5");
if(str != ""){ //체크된 것이 하나라도 있다면(빈칸이 아니다!)
result5.innerText = str;
result5.innerHTML += "<br><br>선택된 개수 : " + count;
//+=을 쓰는 이유 : 위에 값에서 더해준다는 개념
}else{
result5.innerText = "선택된 취미가 없습니다.";
}
}
<div id="cssTest">
<div class="area">Test1</div>
<div class="area">Test2</div>
</div>
<button onclick="fnTest6()">확인하기</button>
funciton fnTest6(){
//id 속성값이 "cssTest"인 요소 1개 선택
//(여러 요소가 있는 경우 첫 번째 요소만 선택
document.querySelector("#cssTest").style.border="3px solid black";
documnet.querySlector("#cssTest > div").style.backgroundColor="gold";
const arr = document.querySelectorAll("#cssTest > div");
for(let i=0; i<arr.length; i++){
arr[i].style.fontSize = '30px;';
}
}
요소접근방법 기억하기!
- js 요소접근하는 방법
: DOM(Document Object Model)을 통해 웹문서(html)의 모든 요소를 객체 형식으로 표현할 수 있다.
- DOM을 이용한 요소 접근방법
1) id 속성값으로 접근하기
2) class 속성값으로 접근하기
3) name 속성값으로 접근하기
4) tag name으로 접근하기
5) CSS선택자를 이용하여 접근하기