18 js에서 html 태그 생성하기

Jo yun hee·2022년 6월 7일

1일1함수외우기

목록 보기
18/18

js에서 html 태그 생성하기

<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title></title>
  </head>
  <body>
    <div id="root">
      <!--js로 html을 만드시오!!!
      <h1 class="ir">테스트페이지</h1>
      <section>
        <h2 class="section-title">섹션제목</h2>
        <img class="section-img" src="img.jpg" alt="섹션이미지">
        <p class="section-contents">내용</p>
      </section>
      -->
    </div>
    <script>
      const root = document.querySelector('#root');
      const h1 = document.createElement('h1');
      h1.setAttribute('class', 'ir');
      h1.textContent = '테스트페이지';
      const section = document.createElement('section');
      const h2 = document.createElement('h2');
      h2.setAttribute('class', 'section-title');
      h2.textContent = '섹션제목';
      const img = document.createElement('img');
      img.setAttribute('class', 'section-img');
      img.setAttribute('src', 'img-jpg');
      img.setAttribute('alt', '섹션이미지');
      const p = document.createElement('p');
      p.setAttribute('class', 'section-contents');
      p.textContent = '내용';

      root.append(h1);
      section.append(h2, img, p);
      root.append(section);
    </script>
  </body>
</html>



0개의 댓글