DOM

jihyun·2021년 8월 5일
0

TIL

목록 보기
3/17
post-thumbnail

DOM?

HTML 문서에 접근하기 위한 프로그래밍 인터페이스

프로그래밍 인터페이스? API? => 여러 소프트웨어 간 상호작용이 가능하게 하는 인터페이스

const startButton = document.querySelector(".startButton");
startButton.textContent = "Hello";

DOM을 통해 화면을 조작할 수 있으나 HTML 파일 자체를 수정하지는 않는다.

HTML 파일 = 설계도, 결과물 = 화면

DOM을 이용해 화면을 조작할 뿐, 설계도는 변하지 않는다.

1. 요소 선택하기

✔️ id

  • document.getElementById("id")

    id는 페이지에서 하나만 존재

✔️ className

  • document.getElementsByClassName("classname")

    결과값이 유사배열 => 배열에 담긴 요소들이 하나의 HTML Element이고, 인덱스로 접근

    해당 클래스를 가진 요소가 하나라도 유사배열

✔️ tagName

  • document.getElementsByTagName("li");

    결과값이 유사배열 => 배열에 담긴 요소들이 하나의 HTML Element이고, 인덱스로 접근

✔️ css 선택자(querySelector) 👍🏻

  • document.querySelector("#color");

    모든 경우에 하나의 요소를 반환 => 여러 개일 경우 첫번째 요소

  • document.querySelectorAll("h1");

    결과값이 유사배열 => 배열에 담긴 요소들이 하나의 HTML Element이고, 인덱스로 접근

Array.from
유사 배열 객체(array-like object)나 반복 가능한 객체(iterable object)를 얕게 복사해 새로운 Array 객체를 생성한다.

const colors = document.getElementsByClassName("jsColor"); //유사배열
console.log(typeof colors); // object -> 객체이지만
console.log(Array.isArray(colors)); // false -> 배열이 아님
Array.from(colors).forEach(color => color.addEventListener("click", handleColorClick) 
); 
// Array.from으로 colors를 복사해 새로운 배열을 생성
// forEach로 각각의 요소(color)에 이벤트 등록

2. 요소 수정

// 요소 수정
const title = document.querySelector("h1");
title.textContent = "This is Title!";

Element.[ClassList]

3. 요소 추가

let title = document.createElement("h1"); // 요소 생성
title = "This is title" // 요소에 대해 텍스트, 글씨크기 등 설정
document.body.append(title); //요소 추가

0개의 댓글