# shadow DOM

Doozuu·2022년 12월 6일
0

Javascript

목록 보기
37/99

Shadow DOM

: 일반적으로는 볼 수 없는 숨겨진 HTML

  • Web Component와 합쳐 쓰면 HTML 모듈화를 할 수 있다.

예시

<input type="range">
  • 내부적으로 여러개의 div를 이용해서 만들어진 것임.
  • 숨겨진 코드를 확인하기 위해서는 개발자도구 -> 설정 -> show user agent DOM 으로 알 수 있다.

Shadow DOM 만드는 법

attachShadow({mode:'open'})

<div class="mordor"></div>
<script>
  document.querySelector('mordor').attachShadow({mode : 'open'});
  document.querySelector('mordor').shadowRoot.innerHTML = '<p>심연에서왔도다</p>'
</script>

Web Component의 단점 : 스타일 오염

HTML

<custom-input></custom-input>
<label>왜 나까지 빨개짐?</label>

JS

class 클래스 extends HTMLElement {
  connectedCallback() {
    this.innerHTML = `<label>이름을 입력하쇼</label><input>
      <style> label { color : red } </style>`
  }
}
customElements.define("custom-input", 클래스);

컴포넌트와 관계없는 다른 태그까지 오염이 발생할 수 있다.

  • 해결방법 : 스타일을 shadow DOM에 넣으면 밖에 영향을 끼치지 않음.

class 클래스 extends HTMLElement {
  connectedCallback() {
    this.attachShadow({mode : 'open'});
    this.shadowRoot.innerHTML = `<label>이름을 입력하쇼</label><input>
      <style> label { color : red } </style>`
  }
}
customElements.define("custom-input", 클래스);

<template> 태그

: 컴포넌트를 만들 때 html이 너무 길어지면 <template> 태그에 잠깐 보관해둘 수 있음.

  • template 태그 안에 적으면 렌더링되지 않음.
  <custom-input></custom-input>

  <template id="template1">
    <label>이메일을 입력하쇼</label><input>
    <style>label { color : red }</style>
  </template>

  <script>
    class 클래스 extends HTMLElement {
      connectedCallback() {
        this.attachShadow({mode : 'open'});
        this.shadowRoot.append(template1.content.cloneNode(true));
      }
    }
    customElements.define("custom-input", 클래스);
  </script>
profile
모든게 새롭고 재밌는 프론트엔드 새싹

0개의 댓글