*get.ElementByID
html을 js로 정보를 가져오거나 변경할 수 있다.
document.getElementByID("string")
-html의 id="string"을 추적하여 하나의 정보를 가져올 수 있다.
| html <body> <h1 id="title"> Grab me! </h1> <script src="app.js"> </script> </body> |
js const title = document.getElementById("title"); console.dir(title); title.innerText = "Got You!"; |
html id=''title" 해당하는 <h1> 태그 정보에 접근
console.dir(title); title에 해당하는 요소들의 정보를 확인할 수 있음 (object로 표시한 element)
title.innerText 정보를 "Got you"로 변경
* html에서 직접 변경하지 않는 이유?
html은 정적인 리소스이고 상황에 따라 결과 화면을 변경하게 해주기 위해 js를 활용하여 html을 변경해준다.
*get.ElementByClassName
html class="hello"에 해당하는 여러개의 요소들의 정보를 array, 배열 형태로 가져온다.
| html <body> <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> <script src="app.js"> </script> </body> |
js const hellos = document.getElementsByClassName("hello"); console.log(hellos); |
| console 창 HTMLCollection(5) [h1.hello, h1.hello, h1.hello, h1.hello, h1.hello] |
|
*get.ElementByTagName
Name 할당 가능. 여려개의 요소들의 정보를 array, 배열 형태로 가져온다.
ClassName, TagName 경우와 같이 array 형태로 가저오면 title.innertext="hello"와 같은 명령 사용못하기 때문에 비선호
그리고 모든 곳에 class와 name 들어가지 않기 때문에 한계가 있음
*querySelector
css방식으로 한가지의 요소를 가져온다.
| const title = document.querySelector("#hello"); const title = document.getElementById("hello"); 결과값은 같다! |
*querySelectorAll
css방식으로 여러개의 요소를 array 형태로 가져온다.
| html <body> <div class="hello"> <h1> Grab me! </h1> </div> <script src="app.js"> </script> </body> |
js const title = document.querySelector(".hello h1"); //const title = document.querySelector(".hello:first-child h1"); console.log(title); |
| console 창 <h1> Grab me! </h1> |
|
const title = document.querySelector(".hello h1"); === hello란 class 내부에 있는 h1을 가져와!
'프론트엔드 > javascript' 카테고리의 다른 글
| javascript (7) - Html, CSS, JavaScript, toggle (0) | 2023.04.03 |
|---|---|
| javascript (6) - click event, window event (0) | 2023.04.03 |
| javascript (4) (0) | 2023.03.31 |
| javascript (3) - object, function 계산기만들기 (0) | 2023.03.30 |
| javascript (2) (0) | 2023.03.30 |