한 걸음씩
[JS][Udemy] DOM 본문
► DOM
- Document Object Model
- 웹 페이지를 구성하는 JS 객체들의 집합
- 문서 : 문서 객체 모델 내 다른 것들처럼 하나의 객체, 자동 생성
1. Selecting
► getElementById()
- id Select
- html의 id 설정된 부분을 선택할 때 사용
- https://developer.mozilla.org/ko/docs/Web/API/Document/getElementById
<!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">
<title>Unicorn</title>
</head>
<body>
<h1 id="mainheading">I ♥ unicorns</h1>
<img src="https://devsprouthosting.com/images/unicorn.jpg" id="unicorn" alt="unicorn">
</body>
</html>
// Select the image element by its id and save it to a variable called image
// Select the h1 by its id and save it to a variable called heading
const image = document.getElementById('unicorn')
const heading = document.getElementById('mainheading')
► getElementsByTagName
- Tag Select
- 배열 같은 객체인 HTML 집합을 반환
- 배열 메서드는 없지만 인덱스나 length, 반복 가능 등의 항목은 있음
- https://developer.mozilla.org/ko/docs/Web/API/Document/getElementsByTagName
► getElementsByClassName
- Class Select
- 배열 같은 객체인 HTML 집합을 반환
- 배열 메서드는 없지만 인덱스나 length, 반복 가능 등의 항목은 있음
- https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
► querySelector ★
- all-in-one method to select a single element
- getElement Selector 보다 좋음
- https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
document.querySelector('h1') // tag select
document.querySelector('#id') // id select
document.querySelector('.class') // class select
►querySelectorAll ★
- returns a collection of matching elements
- 모든 컬렉션을 선택하기 때문에 반복문, 요소 추가등 다양한 기능 사용
- https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
document.querySelectorAll('h1')
document.querySelectorAll('#id')
document.querySelectorAll('.class')
// 타입과 속성으로 선택
const checkbox = document.querySelector('input[type="checkbox"]')
2. Manipulate
- 콘텐츠를 가져오거나 내용을 설정할 수 있음
- 차이점 : https://developer.mozilla.org/ko/docs/Web/API/Node/textContent
► innerHTML
- Element.innerHTML는 이름 그대로 HTML을 반환. 간혹 innerHTML을 사용해 요소의 텍스트를 가져오거나 쓰는 경우가 있지만, HTML로 분석할 필요가 없다는 점에서 textContent의 성능이 더 좋음
- https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
► textContent
- <script>와 <style> 요소를 포함한 모든 요소의 콘텐츠를 가져옴, 사용자를 고려하지 않음
- textContent는 XSS 공격 (en-US)의 위험이 없음
- https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent
<h1>Pickles Are <span>Delicious</span></h1>
// Delicious를 Disgusting로 바꾸기
document.querySelector('span').textContent = 'Disgusting'
► innerText
- innerText는 "사람이 읽을 수 있는" 요소만 처리
- https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText
3. Attributes
document.querySelector('#id').src // src처럼 속성을 선택해 내용을 변경할 수 있다
let nonce = script.getAttribute("nonce"); // getAttribute 메서드를 사용해 속성을 바로 선택할 수 있음
<button>Hello World</button>
// button 태그를 선택해 button 변수에 저장
const button = document.querySelector("button");
// setAttribute 메서드로 button의 name을 helloButton으로 변경
// setAttribute(name, value)
button.setAttribute("name", "helloButton");
// 위의 속성과 같은 결과를 불러옴
button.name = 'helloButton'
>> <button name="helloButton">Hello World</button>
4. 스타일 변경하기
► style
- style을 지정해주지 않으면 DOM에서 작업하기 어려움
- 특히, 많은 스타일을 한 번에 설정하는 경우 좋은 방법이 아님
- css 클래스를 만들어서 클래스로 접근하는게 더 나은 방법
- style 객체를 사용해서 값을 변경하는 방법 가능
// 자주 사용하는 방법은 아님
// 인라인 스타일은 아주 구체적이고 특정하게 적용되기 때문에 주의해야 함
h1.style.color = 'red'
h1.style.fontsize = '3em'
h1.style.border = '2px solid pink'
// 모든 a태그를 선택해서 style color값을 red로 변경할 수 있음
const allLinks = document.querySelector("a");
for (let link of allLinks) {
link.style.color = 'red'
}
► ClassList
- element.classList 그 자체는 읽기 전용 프로퍼티지만 add()와 remove() 메서드를 이용하여 변형할 수 있다
- getAttribute, setAttirbute로 class를 조작하는 것에 비해 간단하다
- 요소에 현재 클래스를 적용하는 손쉬운 방법
- 클래스를 조장하고, 서로 토글하고, 제거하거나 추가하는 방법
- https://developer.mozilla.org/ko/docs/Web/API/Element/classList
공부 더 하기!!
5. 계층 이동
► parentElement
► children
► nextSibling
- 인접한 형제 요소로 이동하게 함
- 다음 요소 이동할 때 사용
- https://developer.mozilla.org/en-US/docs/Web/API/Node/nextSibling
►previousSibling
6.
- 새 요소 자체를 처음부터 만드는 방법
- 새 요소를 만들어서 그걸 페이지 앞이나 뒤에 추가하고 제거하는 것
- 요소 만들기 : https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
► Append / AppendChild
- https://developer.mozilla.org/en-US/docs/Web/API/Element/append
- https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild
- 앞
►insertAdjacentElement
- 앞에서 추가하고 싶은 경우 : https://developer.mozilla.org/en-US/docs/Web/API/Element/prepend
- 사이에 추가하고 싶은 경우 : https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement
► after
► Practice
► remove / removeChild
- https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild
- https://developer.mozilla.org/en-US/docs/Web/API/Element/remove
- remove가 부모 자식 요소를 신경쓰지 않고 삭제하기 때문에 훨씬 효율적임
'JS' 카테고리의 다른 글
[JS][Udemy] pokemon game demo (0) | 2023.03.27 |
---|---|
[TIL] 2303024 (0) | 2023.03.24 |
[JS][Udemy] Params, Spread, Rest, Destructuring (0) | 2023.03.23 |
[JS][Udemy] Array Callback Methods (0) | 2023.03.22 |
[JS][Udemy] JavaScript Functions 2 (0) | 2023.03.21 |