TIL 10/9 : 크롬앱 3강

Rami·2024년 10월 9일

TodayILearn

목록 보기
19/66

3.2 Searching For Elements

선택자

`html`
<div id="hello">
      <h1>Grab me!</h1>
</div>
일때

const hellos = document.querySelector("#hello");
const hellos = document.getElementsById("hello");

두 코드는 같다.
document.querySelector("#hello");
         ========
document.getElementsById("hello");

# id / . class

querySelector를 사용할 때 #.의 사용법

1. CSS 선택자 이해하기

querySelectorCSS 선택자를 사용하여 HTML 요소를 선택합니다. CSS 선택자는 요소를 선택할 때 다음과 같은 규칙을 사용합니다.

  • . (점): 클래스를 선택할 때 사용
  • # (샵): 아이디를 선택할 때 사용
  • 태그 이름: 특정 태그를 선택할 때 사용

이 세 가지 선택자를 조합하여 다양한 요소를 선택할 수 있습니다.

2. 선택자 사용법

1) 클래스 선택자 (.)

  • . (점)으로 시작하는 선택자는 클래스 이름을 기준으로 요소를 선택합니다.
  • 예를 들어, .helloclass="hello"를 가진 요소를 선택합니다.
const element = document.querySelector(".hello");

2) 아이디 선택자 (#)

  • # (샵)으로 시작하는 선택자는 아이디 이름을 기준으로 요소를 선택합니다.
  • 예를 들어, #helloid="hello"를 가진 요소를 선택합니다.
const element = document.querySelector("#hello");

3) 태그 선택자

  • 태그 이름을 그대로 사용하는 선택자는 특정 태그를 기준으로 요소를 선택합니다.
  • 예를 들어, h1은 모든 h1 태그를 선택합니다.
const element = document.querySelector("h1");

3. querySelector 예제 비교

지금 작성해주신 코드를 하나씩 비교하며 설명해드릴게요.

예제 1: const hellos = document.querySelector(".hello h1");

  • .hello클래스 선택자입니다.
  • 이 선택자는 class="hello"를 가진 요소의 자식 요소 중 첫 번째 h1 태그를 선택합니다.
  • 예를 들어:
    <div class="hello">
      <h1>Grab me!</h1>
    </div>
    • 이 경우 h1 태그를 선택합니다.

예제 2: const hellos = document.querySelector("h1");

  • h1태그 선택자입니다.
  • 이 선택자는 문서 전체에서 첫 번째로 나타나는 h1 태그를 선택합니다.
  • 예를 들어:
    <h1>First H1</h1>
    <h1>Second H1</h1>
    • querySelector("h1")"First H1"을 선택합니다.

예제 3: const hellos = document.querySelector("#hello h1");

  • #hello아이디 선택자입니다.
  • 이 선택자는 id="hello"를 가진 요소의 자식 요소 중 첫 번째 h1 태그를 선택합니다.
  • 예를 들어:
    <div id="hello">
      <h1>Grab me!</h1>
    </div>
    • 이 경우 h1 태그를 선택합니다.

4. 선택자 정리

  • #은 아이디를 선택할 때 사용합니다.
    • 예: #myIdid="myId"를 가진 요소
  • .은 클래스를 선택할 때 사용합니다.
    • 예: .myClassclass="myClass"를 가진 요소
  • 태그 이름만 사용하면 태그를 선택할 때 사용합니다.
    • 예: h1 → 모든 h1 태그

5. 언제 #.을 사용할까?

  • 클래스를 기준으로 선택할 때는 .을 사용하세요.
    • 예: class="hello".hello
  • 아이디를 기준으로 선택할 때는 #을 사용하세요.
    • 예: id="hello"#hello
  • 특정 태그만을 선택하고 싶을 때는 태그 이름을 그대로 사용하세요.
    • 예: <h1>h1

6. 조합하여 사용하는 방법

querySelector에서는 CSS 선택자 조합을 사용하여 더 구체적으로 요소를 선택할 수 있습니다.

  • 조합 예시:
    document.querySelector(".container h1"); // `class="container"` 내의 첫 번째 `h1` 요소 선택
    document.querySelector("#main .content h1"); // `id="main"` 내의 `class="content"`의 첫 번째 `h1` 요소 선택
    document.querySelector(".item#special"); // `class="item"`과 `id="special"`을 동시에 가진 요소 선택

3.5 more Events

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

function handleTitleClick(){
    console.log("title was clicked!!");
    title.style.color = "blue";
}

function handleMouseEnter(){
    title.innerText = "mouse enter";
}

function handleMouseLeave(){
    title.innerText = "mouse leave";
}

title.onclick = handleTitleClick;
// title.addEventListener("click", handleTitleClick);

// title.onmouseenter = handleMouseEnter;
title.addEventListener("mouseenter", handleMouseEnter);

title.onmouseleave = handleMouseLeave;
// title.addEventListener("mouseleave", handleMouseLeave);
title.onclick = handleTitleClick;
title.addEventListener("click", handleTitleClick);

title.onmouseenter = handleMouseEnter;
title.addEventListener("mouseenter", handleMouseEnter);

title.onmouseleave = handleMouseLeave;
title.addEventListener("mouseleave", handleMouseLeave);

==> 서로 같은 코드이다.

window.addEventListener("resize", handleWindowResize);
resize는 window에서 사용할 수 있는 이벤트!


3.6 CSS in Javascript

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

function handleTitleClick(){
    if(title.style.color === "blue") {
        title.style.color = "white";
    } else {
        title.style.color = "blue";
    }
    
}

title.addEventListener("click", handleTitleClick);

blue 면 white로
blue가 아니면 blue 로!

=> 코드 개선

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

function handleTitleClick(){
    const currentColor = title.style.color;
    let newColor; 
    if(currentColor === "blue") {
        newColor = "white";
    } else {
        newColor = "blue";
    }
    title.style.color = newColor;
}

title.addEventListener("click", handleTitleClick);

변경

if(title.style.color === "blue") {
        title.style.color = "white";
    } else {
        title.style.color = "blue";
    }

const currentColor = title.style.color;
    let newColor; 
    if(currentColor === "blue") {
        newColor = "white";
    } else {
        newColor = "blue";
    }
    title.style.color = newColor;

로 중복되는 코드 const 와 let (변경될 변수)로 바꿔준다.


3.8 CSS in Javascript part Three

className과 classList의 차이

className : 기존 classname은 지우고 완전히 새로운 것으로 대체

function handleTitleClick(){
    const clickedClass = "clicked";
    if(h1.className === clickedClass){
        h1.className = "";
    } else {
        h1.className = clickedClass;
    }
}

classList : contains, remove, add 등의 다양한 메서드를 통해 기존의 것 유지한 상태로 추가 및 제거

function handleTitleClick(){
    const clickedClass = "clicked";
    if(h1.classList.contains(clickedClass)){
        h1.classList.remove(clickedClass);
    } else {
        h1.classList.add(clickedClass);
    }
}

toggle : 위에 복잡한 코드들을 toggle 하나로 대체

function handleTitleClick(){
    h1.classList.toggle("clicked");
}
profile
YOLO

0개의 댓글