[TS 과제 챌린지] DOM Array Methods - 트러블슈팅

조민호·2023년 10월 27일
0

문자열을 html 요소로 사용

  1. innerHTML 속성을 사용하여 문자열을 HTML 개체로 변환

    <div id="container"></div>
    const container = document.getElementById('container') as HTMLElement;
    
    const htmlString = '<div><p>Hello, world!</p></div>';
    container.innerHTML = htmlString;
    <div id="container">
    	  <div><p>Hello, world!</p></div>
    </div>


innerHTML을 활용해서

문자열을 다른 요소 안에 넣는 것 뿐만 아니라

문자열을 새로운 요소 자체로 변환하는 것도 가능합니다

const htmlString = '<div><p>Hello, world!</p></div>';

const makeNew = (htmlString: string) => {
  const template = document.createElement('template');
  template.innerHTML = htmlString;
  return template.content.firstElementChild;
};

const newElement = makeNew(htmlString);
console.log(newElement); // <div><p>Hello, world!</p></div>


  1. DOMParser() 인터페이스를 사용하여 문자열을 HTML 개체로 변환

    DOMParser를 사용하면 전달된 HTML 문자열을 파싱하여 새로운 Document 객체를 생성합니다.

    <div id="container"></div>
    const container = document.getElementById('container') as HTMLElement;
    
    const useDOMParser = (htmlString: string) => {
      const parser = new DOMParser();
      const doc = parser.parseFromString(htmlString, 'text/html');
      return doc.body.firstChild;
    };
    
    const htmlString = '<div><p>Hello, world!</p></div>';
    
    //위의 htmlString이 HTML요소로 반환
    const newElement = useDOMParser(htmlString) as HTMLElement; 
    
    // 기존 container에 추가
    container.appendChild(newElement);
    <div id="container">
          <div><p>Hello, world!</p></div>
    </div>

    DOMParser객체의 parseFromString()메소드를 사용하게 되면

    Document객체를 반환하게 됩니다

    그렇지만 이 Document객체는 일반적인 웹 페이지 문서와 같은 구조를 가지며, head와 body 요소를 포함하고 있습니다.

    <html>
      <head></head>
      <body>
        <div><p>Hello, world!</p></div>
      </body>
    </html>

    그러므로 doc.body.firstChild를 사용하여 우리가 현재 관심있는

    body의 첫 번째 자식 요소만 반환하는 것입니다

profile
웰시코기발바닥

0개의 댓글