728x90
반응형
js
// id로 접근하기
function accessId(){
const div1 = document.getElementById("div1");
//접근한 요소의 배경색 얻어오기
const bgColor = div1.style.backgroundColor;
// **** 자바스크립트는 문자열 비교시에도 비교 연산자를 사용!!! ***
if(bgColor == "red"){
div1.style.backgroundColor="yellow";
// div1의 배경색을 yellow로 변경
}else{
div1.style.backgroundColor="red";
}
}
// class로 접근하기
function accessClass(){
// 요소를 여러개 접근하는 경우 [배열]형태로 반환됨
const arr = document.getElementsByClassName("div2");
// console.log(arr);
// 인덱스를 이용해서 요소에 하나씩 접근
arr[0].style.backgroundColor = 'skyblue';
arr[0].innerText='첫 번째 요소';
arr[1].style.backgroundColor='pink';
arr[1].innerHTML = '두 번째 요소';
arr[2].style.backgroundColor = 'green';
arr[2].innerText = '세 번째 요소'
}
//태그명으로 접근하기
function accessTagName(){
// 문서 내 모든 li태그 접근(배열 반환)
const arr = document.getElementsByTagName("li");
// 반복문
for(let i=0; i<arr.length; i++){
const num = arr[i].innerText; // 요소에 작성된 내용(숫자)
arr[i].style.backgroundColor="rgb(130,200," + (50*num)+")";
}
}
//input 태그의 값 얻어오기/변경하기
function inputTest(){
const input = document.getElementById("input-test");
console.log(input.value);
//**innerText/innerHTML은
// 요소의 내용(시작태그, 종료태그 사이에 작성된내용)을
// 얻어오거나, 변경할 때만 사용 가능
// ** input은[value]를 이용해서 값을 가져오거나 변경할 수 있음
// input에 작성된 값 변경하기
input.value=''; //빈 문자열 == value지우기
//input에 초점 맞추기 -? focus();
input.focus();
}
//name으로 접근하기
function accessName(){
const hobbyList = document.getElementsByName("hobby");
let str = "";
let count =0;
for(let i=0; i<hobbyList.length; i++){
// *radio/checkbox 전용 속성*
// .checked : 해당 요소가 체크되어있으면 true, 아니면 false 반환
if(hobbyList[i].checked){//현재요소가 체크되어있으면
//str 변수에 value 누적
str += hobbyList[i].value + " ";
count++;// 개수 증가
}
//#name-div에출력
document.getElementById("name-div").innerText=str;
document.getElementById("name-div").innerHTML += "<br>선택된 개수 : "+count;
}
}
//CSS 선택자로 접근하기
function accessCSS(){
//querySelector() : 요소 1개 선택 시 사용
// (여러 요소가 선택되면 첫 번쨰 요소만 선택)
//1개만 있는 요소 선택
document.querySelector("#css-div").style.border ="2px solid red";
// 여러개 있는 요소 선택)(첫 번째 요소 선택 확인)
document.querySelector("#css-div > div").style.fontSize="30px";
//querySelectorAll() : 모든 요소 선택 시 사용
const arr = document.querySelectorAll("#css-div > div");
//배경색을 원하는 색상으로 바꾸고 실행
for(let i=0; i<arr.length; i++){
arr[i].style.backgroundColor="red";
}
}
/* 카카오톡 채팅 만들기 */
function readValue(){
// 채팅 입력에 사용되는 모든 요소 얻어오기
const bg = document.getElementById("chatting-bg");
const input = document.querySelector("#chatting-input");
//input에 입력된 값이 있을 경우
if(input.value.trim().length >0){
// 문자열.trim() :문자열 양 끝에 공백 모두 제거
// ex) " k h ".trim() -> "K h"
//input에 입력된 값을 얻어와 bg에추가
bg.innerHTML += " <p> <span>" +input.value+"</span></p>";
bg.scrollTop = bg.scrollHeight;
}
// input에 작성된 값 변경하기
input.value = "";
//input에 초점 맞추기
input.focus();
}
// input 태그 키가 눌러졌을 때 엔터인 경우를 검사하는 함수
function inputEnter(event){
console.log(event.key); //현재 눌러진 키를 반환
if(event.key=="Enter"){//눌러진 key가 enter인 경우
readValue(); //함수호출
}
}
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>03_요소접근방법</title>
<script src="js/03_요소접근방법.js"></script>
<style>
.area{
width:300px;
height:100px;
border: 1px solid black;
}
/* 채팅 만들기 */
#chatting-bg{
width:360px;
height:400px;
border:1px solid black;
background-color: rgb(178, 199, 217);
overflow: auto;
}
/* 채팅내용 */
#chatting-bg>p>span{
background-color: rgb(254,234,51);
padding:5px;
border-radius: 5px;
}
/* 채팅 출력 라인 */
#chatting-bg>p{
text-align: right;
margin: 20px 10px;
}
</style>
</head>
<body>
<h1>DOM(Document Object Model)</h1>
<pre>
웹 문서(HTML)의 모든 요소를 객체 형식으로 표현한 것
-> 문서 내 특정 요소에 접근하는 방법을 제공
</pre>
<hr>
<h1>DOM을 이용한 HTML 요소 접근하기(해당 요소객체 가져오기)</h1>
<pre>
1. id로 접근하기 : document.getElementById("id속성값");
<!-- 같은 name,class,tag은 여러 요소가 가질 수 있으므로 복수(Elemnets)로 작성 -->
2. name으로 접근하기 : document.getElementsByName("name속성값");
3. class로 접근하기 : document.getElementsByClassName("class속성값");
4. tag로 접근하기 : document.getElementsByTagName("태그명");
5. CSS 선택자로 접근하기
1) document.querySelector("CSS 선택자");
-> 선택된 요소가 여러 개일 경우 첫 번째 요소만 접근하기
2) document.querySelectorAll("CSS 선택자");
-> 선택된 요소 모두 접근
</pre>
<h3>id로 접근하기</h3>
<button onclick="accessId()">클릭할 때 마다 배경색 변경</button>
<div id="div1" class="area"></div>
<hr>
<h3>class로 접근하기</h3>
<div class="area div2"></div>
<div class="area div2"></div>
<div class="area div2"></div>
<button onclick="accessClass()">배경색 변경하기</button>
<hr>
<h3>태그명으로 접근하기</h3>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<button onclick="accessTagName()">배경색 변경</button>
<hr>
<h1>input 태그의 값(value)얻어오기/변경하기</h1>
<input type="text" id="input-test">
<button onclick="inputTest()">입력</button>
<hr>
<h3>name으로 접근하기</h3>
<table>
<tr>
<td>
<input type="checkbox" name="hobby" id="game" value="게임">
<label for="game">게임</label>
</td>
<td>
<input type="checkbox" name="hobby" id="music" value="음악감상">
<label for="music">음악감상</label>
</td>
<td>
<input type="checkbox" name="hobby" id="movie" value="영화감상">
<label for="movie">영화감상</label>
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="hobby" id="coding" value="코딩">
<label for="coding">코딩</label>
</td>
<td>
<input type="checkbox" name="hobby" id="exercise" value="운동">
<label for="exercise">운동</label>
</td>
<td>
<input type="checkbox" name="hobby" id="book" value="독서">
<label for="book">독서</label>
</td>
</tr>
</table>
<div class="area" id="name-div"></div>
<button onclick="accessName()">출력하기</button>
<hr>
<h3>CSS 선택자로 접근하기</h3>
<div id="css-div">
<div class="area">test1</div>
<div class="area">test2</div>
</div>
<button onclick="accessCSS()">확인하기</button>
<hr>
<div id="chatting-bg">
<p> <span>입력되는 채팅</span></p>
<p> <span>입력되는 채팅</span></p>
<p> <span>입력되는 채팅</span></p>
</div>
<!-- onkeydown : 키가 눌러졌을 때 -->
<!-- onkeypress : 키가 눌러지고 있을 때-->
<!-- 쭉 누르고 있으면 무분별한 함수 호출이 발생 -->
<!-- onkeyup : 키가 올라올때 -->
<input type="text" id="chatting-input" onkeyup="inputEnter(event)">
<!-- envet: 발생한 이벤트에 대한 정보를 담고 있는 객체 -->
<button onclick = "readValue()">입력</button>
</body>
</html>
728x90
반응형
'괴발개발 > js' 카테고리의 다른 글
| 문자열 숫자형 변환 (0) | 2024.06.18 |
|---|---|
| 정규표현식 (0) | 2024.06.17 |
| 자바스크립트 js 이벤트 (0) | 2024.06.14 |
| 데이터 입출력 (0) | 2024.06.13 |
| javascript 개요 (1) | 2024.06.12 |