๐Ÿ’ป๐Ÿ’€/๊ฐœ๋ฐœ

[JS] JavaScript์—์„œ HTML ์š”์†Œ๋ฅผ ๋งŒ๋“œ๋Š” 3๊ฐ€์ง€ ๋ฐฉ๋ฒ•

db2 2022. 10. 2. 19:39

์ด ๊ธ€์€ 3 Ways To Create HTML Element In JavaScript์„ ์ฐธ๊ณ ํ•˜์—ฌ ์ž‘์„ฑ๋œ ๊ธ€์ž…๋‹ˆ๋‹ค.

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ๋ฅผ ํ†ตํ•ด ์•„๋ž˜์™€ ๊ฐ™์€ ๊ตฌ์กฐ๋ฅผ ๊ฐ–๋Š” DOM์„ ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ• 3๊ฐ€์ง€๋ฅผ ์•Œ์•„๋ณด์ž.

<body>
  <div id="app">
    <button id="button">Click Me!</button>
  </div>
</body>

1. createElement() ์‚ฌ์šฉํ•˜๊ธฐ

๋จผ์ € body์— app ์š”์†Œ๋ฅผ ์ถ”๊ฐ€ํ•œ๋‹ค.

const app = document.createElement('div');
app.id = 'app';
document.body.appendChild(div);

๊ทธ๋ฆฌ๊ณ  app์— button ์š”์†Œ๋ฅผ ์ถ”๊ฐ€ํ•œ๋‹ค.

const button = document.createElement('button');
button.id = 'button';
button.innerText = 'Click Me!';
app.appendChild(button);

2. Object.assign() ์‚ฌ์šฉํ•˜๊ธฐ

body์— app ์š”์†Œ๋ฅผ ์ถ”๊ฐ€ํ•œ๋‹ค.

const app = Object.assign(
    document.createElement('div'),
      { id: 'app' }
);

document.body.appendChild(app);

๊ทธ๋ฆฌ๊ณ  app์— button ์š”์†Œ๋ฅผ ์ถ”๊ฐ€ํ•œ๋‹ค.

const button = Object.assign(
    document.createElement('button'),
      { 
        id: 'button',
        innerText: 'Click Me!'
    }
);
app.appendChild(button);

ํ˜น์€ appendChild์˜ ๋ฉ”์„œ๋“œ ์ฒด์ด๋‹์„ ํ†ตํ•ด ํ•œ ๋ฒˆ์— ์ถ”๊ฐ€ํ•ด ์ค„ ์ˆ˜๋„ ์žˆ๋‹ค.

document.body.appendChild(app).appendChild(button);

Template literals

๋ฐฑํ‹ฑ ์•ˆ์— HTML ์ฝ”๋“œ๋ฅผ ๊ทธ๋Œ€๋กœ ์ž…๋ ฅํ•œ ๋’ค innerHTML์„ ํ†ตํ•ด DOM์— ์ถ”๊ฐ€ํ•œ๋‹ค.

const app = `
    <div id="box">
        <button id="button">Click Me!</button>
    </div>
`;
document.body.innerHTML = app;