JS DOM 실습

FE 개발자 신상오·2022년 5월 17일
0

JS

목록 보기
7/15
post-thumbnail

DOM


DOM 실습 코드

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="stylesheet" href="style.css" />
        <title>Document</title>
    </head>
    <body>
        <div id="container">
            <h2>Tweet List</h2>
            <div class="tweet">hello</div>
            <div class="tweet">world</div>
            <div class="tweet">code</div>
            <div class="tweet">states</div>
        </div>
    </body>
</html>

<Script>

  1. head 안쪽에 추가
  2. body 맨 끝에 추가

body 태그 최하단에 추가하는 게 좋은 이유

<참고자료> : https://bit.ly/3lews1E

자바스크립트에서 dom은 document 객체에 구현되어 있습니다
따라서 브라우저에서 작동되는 자바스크립트 코드에서는 어디에서나 document 객체를
조회할 수 있습니다.

DOM 구조를 조회할 때는 DOM을 객체의 모습으로 출력하는 console.dir이 유용합니다.


JS 부모, 자식, 형제 찾기

<참고자료> : https://itun.tistory.com/501

DOM 실습

CREATE


1 document.createElement('div')
 // document 객체의 createElement 메서드를 이용하여<div> 요소 생성


2 const tweetDiv = document.createElement('div')
 //새로 생성한 div 요소를 변수에 할당

➡️
createElement 메서드로 생성된 엘리먼트는 공중에 떠있는 상태이므로
APPEND를 이용해 트리 구조에 연결해야합니다



APPEND

1 document.body.append(tweetDiv)
 //document body요소에 tweetDiv 요소 추가



READ

자바스크립트에서 원시 자료형인 변수의 값을 조회하기 위해서는 변수의 이름으로 직접 조회 가능
참조자료형인 배열은 index를 객체는 key를 이용해 값을 조회

DOM으로 HTML 엘리먼트의 정보를 조회하기 위해서는 querySelector의 첫 번째 인자로 셀렉터를 전달하여 확인합니다
가장 많이 사용하는 셀렉터
1. HTML 요소
2. id
3. class

querySelector - 셀렉터 조회

1 const oneTweet = document.querySelector('.tweet')
  // 클래스 이름이 `tweet`인 HTML 요소 중 첫 번째 요소를 
  // oneTweet 변수에 할당

querySelectorAll - 여러 요소를 한 번에 가져오는 명령어

1 const tweets = document.querySelectorAll('.tweet')
  // 클래스 이름이 tweet인 모든 HTML 요소를 유사 배열로 받아옵니다.

⚠️ 유사배열(Array-like Object)이란?
querySelectorAll을 사용해 조회한 HTML 요소들은 배열처처럼 for문이 사용 가능하지만
조회한 HTML 요소들은 배열이 아닙니다
이런 '배열 아닌 배열'을 유사배열, 배열형 객체 등 다양한 이름으로 부릅니다

getElementByID    VS    querySelector

1 const getOneTweet = document.getElementById('container')
2 const queryOneTweet = document.querySelector('#container')
3 console.log(getOneTweet === queryOneTweet) // true

// 위의 두 명령어로 받아온 container 요소는 같다

container의 맨 마지막 자식 요소로 tweetDiv를 추가

const container = document.querySelector('#container')
const tweetDiv = document.createElement('div')
container.append(tweetDiv)



UPDATE

const oneDiv = document.createElement('div');
// div 요소 생성해 변수 oneDiv에 할당 -> <div></div>
oneDiv.textContent = 'dev';
// textContent 이용해 문자열 입력 -> <div>dev</div>
oneDiv.classList.add('tweet')
// classList 이용해 클래스 추가 -> <div class = "tweet">dev<div>


const container = document.querySelector('#container')
container.append(oneDiv)
// container 클래스를 가지는 부모요소에 
// 위에서 생성된 요소를 자식요소로 추가



DELETE

요소를 삭제하는 방법에도 여러가지가 있습니다

1. 삭제하려는 요소의 위치를 알고있는 경우 - remove

const container = document.querySelector('#container')
const tweetDiv = document.createElement('div')
container.append(tweetDiv)
tweetDiv.remove() 
// 이렇게 append 했던 요소를 삭제할 수 있다.

2. 여러 개의 자식 요소 지우기 - innerHTML

document.querySelector('#container').innerHTML = '';
// id가 contaioner인 모든 요소를 지웁니다.

innerHTML 은 간편하하지만 보안에서 몇 가지 문제를 가지고 있습니다.
https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#security_considerations

3. innerHTML을 보완해 대신할 메서드 - removeChild

자식 요소를 지정해서 삭제하는 메서드로 모든 자식 요소를 삭제하기 위해
반복문 (while, for)을 활용할 수 있습니다

  • 모든 자식 요소 제거
const container = document.querySelector('#container');
while (container.firstChild) {
  container.removeChild(container.firstChild);
}
// 자식 요소가 남아있지 않을 때까지 첫 번째 자식요소를 삭제하는 반복문 코드
  • 자식 요소 1개 남을 때까지 자식 요소 제거
const container = document.querySelector('#container');
while (container.children.length > 1) {
  container.removeChild(container.lastChild);
}

4. 클래스명을 이용한 제거

const tweets = document.querySelectorAll('.tweet')
tweets.forEach(function(tweet){
    tweet.remove();
})
// or
for (let tweet of tweets){
    tweet.remove()
}
profile
주간 회고용 블로그입니다 (개발일지와 정보글은 티스토리에 작성합니다.)

0개의 댓글