0222 TIL DOM 조작

냐하호후·2022년 2월 22일
0

TIL

목록 보기
100/101

Create

  1. 새로운 div element만들기
    const tweet = document.createElement('div')
    append를 해주지 않으면 div엘리먼트 tweet이 만들어지긴 했지만 연결되어있지 않아서 실제로 보이지가 않는다.
  2. append 메소드를 이용해 변수 tweet을 body엘리먼트에 넣기
    document.body.append(tweet)

Read

querySelector

DOM으로 HTML엘리먼트 정보를 조회하기 위해서는 첫번째 인자로 셀렉터를 전달해 확인할 수 있다.
셀렉터로 HTML태그("div")/id("#tweetList")/class(.tweet)가 가장 많이 사용된다.

여러개의 엘리먼트를 한번에 가져올 때는 querySelectorAll을 사용한다.
const tweets = document.querySelectorAll('.tweet')

Update

textContent

textContent 메서드를 이용해서 빈 태그속에 문자열을 입력할 수 있다.

console.log(oneDiv) // <div></div>
oneDiv.textContent = 'dev';
console.log(oneDiv) // <div>dev</div>

classList

classList를 이용해서 클래스를 추가해 줄 수 있다.

oneDiv.classList.add('tweet')
console.log(oneDiv) // <div class="tweet">dev</div>

setAttribute를 통해 속성값을 줄 수 있다.
<button>Hello World</button>
이렇게 존재할 때

let b = document.querySelector("button");

b.setAttribute("name", "helloButton");

콘솔을 쳐보면
<button name = "helloButton">Hello World</button>

Delete

삭제하려는 엘리먼트의 위치를 알 경우, remove 메소드를 이용할 수 있다.

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

여러 자식 엘리먼트를 지우고 싶을 때 innerHTML을 사용하면 편리하다.
document.querySelector('#container').innerHTML = '';
하지만 보안 문제를 겪게 될 수 있기때문에 반복문을 이용해서 삭제해 주는 방법이 더 좋다.

const container = document.querySelector('#container');
while (container.children.length > 1) {
  container.removeChild(container.lastChild);
}
profile
DONE is better than PERFECT

0개의 댓글