하루를살자

JS - Vanilla JS Clone Project [JS with DOM] 본문

JS

JS - Vanilla JS Clone Project [JS with DOM]

Kai1996 2021. 12. 2. 09:20

Html 의 Elements 들은 JS 로 tag 타입 이나 class, ID 로 접근할수 있다. 

가장 기본적인 예로 

index.html 에 title 이란 ID 를 h1 tag 로 만들어서 console.dir() 을 아래와 같이 해볼 것 이다. 

 

-index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    
    <title>Momentum</title>
</head>
<body>
    <h1 id = "title">Grab Me!</h1>
    <script src = "app.js"></script>
</body>
</html>

-app.js

const title = document.getElementById("title");

console.dir(title);

dir 은 자바스크립트 오브젝트 가 가지고 있는 모든 properties 를 볼수 있게 하는 메소드이고 <h1> 테그가 가지고 있는 모든 properties 들을 console 에 보여준다. 이 프로퍼티 들 은 테그 를 맨 처음 쓸 때 값을 주어도 무방하고, JS 로 동적인 효과를 줄 때도 사용이 가능하다. 

 

ex) 

const title = document.getElementById("title");

console.log(title);

title.innerText = "Gotya";

 

html 의 요소를 선택할때, document.get~ 방식말고도 다른방법들이 많은데, 이 프로젝트에서는 CSS 요소 선택방식과 같은 document.querySelector() 를 쓸것이다. 

여기서 중요한점은, class 이름을 refer 할떄, '.' 을 CSS 처럼 앞에 붙혀줘야한다. 

ID 는 '#' 를붙혀주고 

기본테그는 아무것도 안붙힘. 

*만약 중복된 div class 이름이 있을경우, querySelector 는 첫번째의 class 를 참조하게된다. 

모든 class (같은 이름) 를 선택하고 싶다면, querySelectorAll() 를 쓰는게 바람직하다.  

const title = document.getElementById("title");
const title2 = document.querySelector(".h1");

console.log(title.innerText);
console.log(title2.innerText);
//위 두개의 선택자는 같은결과를 줌

 

Comments