본문 바로가기

HTML, CSS, Javascript

[Javascript] HTML 문서에 새 요소 붙이는 방법

HTML 문서에 새 요소를 붙이는 방법은 Javascript로 구현할 수 있다.

  1. 우선, 새 요소를 생성한다.
  2. 부모 요소를 찾는다.
  3. 새 요소를 부모 요소에 붙여준다.

 

index.html :

더보기
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>practice</title>
  </head>
  <body>
    <div id="parent"></div>
  </body>
</html>

parent id를 갖는 div 태그 자식 요소로 추가한다.

 

 

새 요소 생성, document.createElement(요소) :

DOM에서 새 HTML 요소를 javascript로 생성할 때 사용한다.

더보기
const child = document.createElement("div");

div 요소를 만들어 준다.

 

const img = document.createElement('img');
img.src = 'image.jpg';
img.alt = '설명 텍스트';
img.style.width = '100px';

HTML 요소 생성 후, 속성(attribute) 추가도 할 수 있다.

 

 

부모 요소 가져오기 :

더보기
const parent = document.getElementById("parent");

요소를 가져오는 자세한 내용은 : 

https://kimyongjun0129.tistory.com/94

 

 

요소 붙이기 :

더보기
parent.appendChild(child);

요소를 붙이는 자세한 내용은 : 

https://kimyongjun0129.tistory.com/97

 

 

전체 코드 : 

더보기
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>practice</title>
  </head>
  <body>
    <div id="parent"></div>
  </body>
  <script>
    const parent = document.getElementById("parent");

    const child = document.createElement("div");
    parent.appendChild(child);
  </script>
</html>

 

 

결과 :

결과