01. JavaScript를 사용하는 이유
- HTML과 상호작용하기 위해서
-> HTML의 Element를 JS를 통해 변경하고 읽을 수 있음
* Browser의 핵심 object : document
- JS는 HTML document 객체로부터 title이란 요소를 가지고 올 수 있음 (document.title -> "Momentum")
-> JS는 HTML에 접근하고 읽을 수 있게 설정되어 있음
* object 의 properities는 변경 가능함
-> JS에서는 어떻게?
- JS에서도 변경 가능! (새로고침하면 다시 되돌아감 Hello -> Momentum)
02. The way to access elements in HTML from JavaScript
1. getElementById("Id")
const title = document.getElementById("title");
console.log(title); //<h1 id="title">Grab me!</h1>
console.log(title.id); //title
console.dir(title);
** console.log()와 console.dir()의 차이점
1. console.log()
- element를 HTML과 같은 트리 구조를 출력
- DOM(Document Object Model) 요소에 대한 특별한 처리 제공
2. console.dir()
- element를 JSON과 같은 트리 구조를 출력
- DOM JS 객체의 전체 표현을 보려고 할 때 유용
* JS -> HTML -> JS
- HTML의 element를 JS에서 다룸
- JS는 HTML element를 가져오지만 HTML 자체를 보여주지는 않음
=> id를 활용하여 JS의 getElementById()라는 함수를 통해 document(HTML)이란 object의 properities를 변경할 수 있음
2. getElementByClassName("ClassName")
// in HTML
<h1 class="hello">Grab me!</h1>
<h1 class="hello">Grab me!</h1>
<h1 class="hello">Grab me!</h1>
<h1 class="hello">Grab me!</h1>
<h1 class="hello">Grab me!</h1>
=============================================
// in JavaScript
const hellos = document.getElementsByClassName("hello");
console.dir(hellos);
3. querySelector()
- element를 CSS 방식으로 검색할 수 있게 함
//in HTML
<div class="hello">
<h1>Grab me!</h1>
</div>
==================================
//in JavaScript
const title = document.querySelector(".hello h1");
// ".hello h1" : css selector
console.log(title); // <h1>Grab me!</h1>
- 동일한 className을 지닌 class의 요소가 여러 개 있을 경우 첫번째 요소만 가져다 줌
-> querySelectorAll() 을 사용하여 class의 모든 요소를 가져오게 할 수 있음
[JS]03. Login 2 (1) | 2023.10.10 |
---|---|
[JS]03. Login 1 (0) | 2023.10.10 |
[JS]02. JavaScript on the Browser 3 (0) | 2023.10.07 |
[JS]02. JavaScript on the Browser 2 (0) | 2023.10.07 |
[JS]01. 기본 문법 (0) | 2023.09.13 |
댓글 영역