보다 더 생생한 기록

DOM(Document Object Model) 본문

블록체인

DOM(Document Object Model)

viviviviviid 2022. 7. 30. 15:58

DOM의 특징

  • 자바스크립트를 사용할 수 있는 유저이면, DOM으로 HTML을 조작할 수 있다.
  • DOM은 자바스크립트 언어 일부가 아니라 웹사이트를 구축하는데 사용되는 API이다.
  • DOM을 사용하기위해 특별히 해야할 것은 없다.
  • 웹브라우저가 작성된 코드를 해석하는 과정에서 <script></script> 요소를 만나면 HTML 해석을 잠시 멈추고 <script>부터 실행 된다.

 

<script>
       // run this function when the document is loaded
       window.onload = function() {

         // create a couple of elements in an otherwise empty HTML page
         var heading = document.createElement("h1");
         var heading_text = document.createTextNode("Big Head!");
         heading.appendChild(heading_text);
         document.body.appendChild(heading);
      }
</script>

 

위와 같이 자바스크립트 내에서 작업하며, HTML을 직접 건들지 않고도 자바스크립트를 통해 HTML의 요소등을 생성, 수정할 수 있다.

 

이제 실습해보자.

 

1. 생성된 다양한 엘리먼트 중, 하위에서 뭔가를 찾고싶다? 

document.body.children // console.dir을 사용하는 것도 좋은 방법이다.

2. 엘리먼트를 생성하고 싶다?

const tweetDiv = document.createElement('div') 
// createElement 메소드를 사용하여 div 를 생성하고 tweetDiv 에 할당합니다.

3. 2번에서 만든 엘리먼트를 특정 위치에 삽입하고 싶다?

document.body.append(tweetDiv)
// 변수 tweetDiv에 담긴 새로운 div 엘리먼트를 body 엘리먼트에 append 합니다.

4.특정 엘리먼트를 조회하여 새로이 변수를 만들어 이용하고 싶다?

const oneTweet = document.querySelector('.tweet')
// 클래스이름이 tweet인 HTML 엘리먼트 중 첫번째를 oneTweet 변수에 할당한다.
const getOneTweet = document.getElementById('.tweet')
// 결과는 같지만 이전 버전과의 호환성을 신경써야한다면 알아둬야 함.

5. 하나만 가져오는 4번과 다르게 전체를 가져오고 싶다?

const tweets = document.querySelectorAll('.tweet')
// 클래스이름이 tweet인 HTML 엘리먼트 내의 것을 한번에 가져와서 tweets에 할당한다.


6. 특정요소내에 텍스트를 삽입하고 싶다?

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

7. 엘리먼트를 삭제하고 싶다?

tweetDiv.remove() //append 했던 tweetDiv를 삭제할 수 있다.

8. 그 외에 여러가지 삭제하는 방법 (ex 하위 엘리먼트를 전부 삭제하고 싶다 등은 구글링 할 것)

 

 

 

'블록체인' 카테고리의 다른 글

고차 함수 - (3) [자주 까먹는 메소드]  (0) 2022.07.31
고차 함수 - (2) [filter, map, reduce ...]  (0) 2022.07.30
고차 함수 - (1)  (0) 2022.07.30
Linux (.etc)  (0) 2022.07.11
BootCamp - BlockChain 6th  (0) 2022.07.07