Front/JavaScript

JavaScript) 동적으로 HTML 태그 생성하기

pogun 2025. 2. 20. 23:30

1. HTML 기본 구조 설정

<button type="button" onclick="makeElement()">태그 작성</button>
<br/>
<div id="demo"></div>

: <button>: 사용자가 클릭하면 makeElement() 함수를 실행하여 태그를 생성

: <br/>: 줄 바꿈 역할

: <div id="demo">: 새로운 요소들을 추가할 영역


2. makeElement() 함수: 새로운 HTML 요소 생성

기능 설명
document.createElement("태그명") 새로운 HTML 요소 생성
element.innerHTML = "내용" 요소 안에 텍스트 삽입
document.body.appendChild(요소) <body>에 요소 추가
document.getElementById("id").appendChild(요소) 특정 id를 가진 요소에 추가
element.setAttribute("속성", "값") 속성 설정 (input의 type, placeholder 등)
addEventListener("이벤트", 함수명) 이벤트 리스너 추가
function makeElement() {
    // <p> 태그 생성
    const ptag = document.createElement("p");  // <p></p>
    ptag.innerHTML = "Hello P tag";  // <p>Hello P tag</p>
    document.body.appendChild(ptag);
    
    // <button> 태그 생성
    const button = document.createElement("button");
    button.innerHTML = "클릭하시오!";
    button.addEventListener("click", buttonClick);
    document.body.appendChild(button);
    
    // <input> 태그 생성
    const input = document.createElement("input");
    input.setAttribute("type", "text");
    input.setAttribute("placeholder", "이름입력");
    input.setAttribute("id", "name");
    
    document.getElementById("demo").appendChild(input);
}

 

2-1. <p> 태그 생성

const ptag = document.createElement("p");  // <p></p>
ptag.innerHTML = "Hello P tag";  // <p>Hello P tag</p>
document.body.appendChild(ptag);

: document.createElement("p")를 사용하여 <p> 요소를 만든다.

: innerHTML을 이용해 <p> 태그 내부에 "Hello P tag" 문자열을 추가

: document.body.appendChild(ptag)를 사용하여 HTML 문서의 <body>에 추가

2-2. <button> 태그 생성 및 이벤트 추가

function makeElement(){
    const button = document.createElement("button");
    button.innerHTML = "클릭하시오!";
    button.addEventListener("click", buttonClick);
    document.body.appendChild(button);
}

const buttonClick = () => {
    console.log('buttonClick!!');
}

: document.createElement("button")을 사용하여 <button> 요소를 만든다.

: innerHTML을 이용해 버튼 내부에 "클릭하시오!" 텍스트를 삽입한다.

: addEventListener("click", buttonClick)를 통해 클릭 이벤트를 추가

: document.body.appendChild(button)를 사용하여 <body>에 버튼을 추가

2-3. <input> 태그 생성

const input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("placeholder", "이름입력");
input.setAttribute("id", "name");

document.getElementById("demo").appendChild(input);

: document.createElement("input")을 사용하여 <input> 요소를 만든다.

: setAttribute("type", "text")를 사용해 type="text" 속성을 설정

: setAttribute("placeholder", "이름입력")을 통해 "이름입력"이라는 플레이스홀더를 추가

: setAttribute("id", "name")을 사용해 id="name"을 설정

: document.getElementById("demo").appendChild(input)을 사용하여 <div id="demo">에 추가