JavaScript

Learn JavaScript _1

그레고리 2022. 1. 6. 20:24
728x90

- 보편적으로 id만 쓰는 일은 거의 없고, class를 쓰거나 class와 id를 같이 사용한다. 

 

- querySelector() : element를 CSS방식으로 검색할 수 있다. 

 ()내에는 css문법을 생각하고 적으면 된다. (id인 경의 #name, class의 경우 .name) 키워드 간은 띄어쓰기로 구분된다. 

 검색 결과, element를 찾지 못하면 null을 반환한다. 

 element를 가져올 때, 대부분 querySelector를 사용하는 것이 좋다. 

docuemnt.querySelector();
docuemnt.querySelectorAll();

//JS
const title = document.querySelector(".hello h1");

//HTML
<div class="hello">
	<h1> hello </h1>
</div>

//className이 hello인 tag 내의 h1을 불러온다.
//만약 hello안에 h1이 여러개가 있으면 기본적으로는 첫번째만 반환한다.
//여러개를 array로 반환받고 싶으면 querySelectorAll()을 사용해야한다.
//() 안은 css selector가 사용된다. 아래 세개는 모두 같다. 
querySelector(".hello h1");
querySelector(".hello:first-child h1");
querySelector("div.hello:first-child h1");

 

 

- JavaScript Object

console.log(element) 말고 console.dir(element) 을 사용하면 element를 object로 반환한다. 

element object

여기에 보이는 항목들 모두 javaScript object내의 property항목들 이다. (on붙은 것들은 event)

property들은 title.style.color = "blue" 이런식으로 바꿀 수 있다. (style도, color도 모두 property)

 

- add Event on object

예시: 타이틀 element를 클릭하면 함수가 실행된다. 

//element가져오기 
const title = document.querySelector(".hello h1"); 
//click시 실행될 func
function handleTitleClick(){
    console.log("title was clicked");
}
//object에 eventLister 붙이기 
title.addEventListener("click", handleTitleClick);

- event를 찾는 방법

1. Web API 홈페이지를 참조하는 것.

https://developer.mozilla.org/ko/docs/Web/API/HTMLElement

 

HTMLElement - Web API | MDN

HTMLElement 인터페이스는 모든 종류의 HTML 요소를 나타냅니다. 일부 요소는 이 인터페이스를 직접 구현하지만 나머지 요소는 HTMLElement를 상속한 자식 인터페이스를 구현합니다.

developer.mozilla.org

2. console.dir(element)를 해서, 콘솔에서 보는 것. 여기서 on으로 시작되는 것들이 대부분 event이고, 쓸때는 on 빼고 "click"이런식으로 쓰면됨. 

여기서 on 어쩌구는 다 event

- style은 js에서 잘 안바꾸고 보통 CSS에서 해결한다. 

728x90