Document Object에 대해 알아보자.
웹페이지가 문서를 읽으면 window 객체를 만든다. window객체는 최상위 객체로 6개의 프로퍼티를 가지고 있다. (document, navigator, screen, location, frames, history)
그리고 html코드(images, anchor)등을 javascript 정보로 가지고 있는 객체가 document 객체이다.
Dom객체를 사용하는 이유는 html 태그에 이벤트를 추가하거나 내용을 변경할 때 사용한다.
.querySelector()는 CSS 선택자로 요소를 선택하게 해준다. html내에 있는 모든 태그들에게 동적 움직임을 제공한다. 다만 주의할 점은 선택자에 해당하는 첫번째 요소만 선택한다는 것이다.
예를 들어보자
ex)
<body>
<h1>제목 바꾸기</h1>
<button onclick="move();">바꾸기</button>
<script>
let move = () => {
document.querySelector("h1").innerText = "제목 바꾸기 성공!";
}
</script>
</body>
바꾸기 버튼을 누르면 h1태그내부의 '제목 바꾸기'가 '제목 바꾸기 성공'으로 바뀐다.
하지만
<body>
<h1>제목 바꾸기</h1>
<h1>이것도 바뀌나요?</h1>
<button onclick="move();">바꾸기</button>
<script>
let move = () => {
document.querySelector("h1").innerText = "제목 바꾸기 성공!";
}
</script>
</body>
에서의 '이것도 바뀌나요?'는 바뀌지 않는다. querySelector()는 첫번째 요소만 선택하기 때문이다. 그렇다면 같은 태그내에서의 값을 모두 바꾸려면 어떻게 해야할까?
이 함수는 특정 CSS 선택자를 가진 모든 요소를 배열로 가져오는 메서드이다.
메서드의 반환타입이 Array type 이므로 인덱스를 이용해 요소에 변화를 준다.
ex)
<body>
<h1 id="colorch1">색 바꾸기</h1>
<h1 id="colorch2">색 바꾸기</h1>
<button onclick="change();">바꾸기</button>
<script>
let change = () => {
for(let i=0; i<2; i++)
document.querySelectorAll("h1")[i].style.color = "green";
}
</script>
</body>
document.querySelectorAll("h1").style.color = "green"; 을 작성하면 적용이 안된다. document.querySelectorAll("h1")까지의 함수반환타입이 Array type이기 때문에 .으로 접근하면 안되고 []로 접근해야한다.
그 외의 다양한 메서드들이 Object들이 존재한다
document.querySelector().value : 웹페이지 내에 사용자가 입력한 값들과 관련
ex)
<body>
<div>
<label for="id">아이디</label>
<input type="text" name="id" id="one">
<label for="psw">비밀번호</label>
<input type="password" name="psw" id="two"><br>
<button onclick="copy();">복사</button>
</div>
<script>
let copy = () => {
let Idinformation = document.querySelector("#one").value;
document.querySelector("#two").value = Idinformation;
}
</script>
</body>
아이디에 입력한 값이 복사버튼을 누를 시, 비밀번호 텍스트에 복사된다.
document.querySelector().style.color : 글자색 바꾸기
document.querySelector().style.backgroundColor: 배경색 바꾸기
document.querySelector().style.display = "none"; : 요소내용 사라짐
document.querySelector("p").style.display = "block"; : 블럭형태로 다시생김
document.querySelector("p").style.fontSize = "50px"; : 글자크기 변경