์ด ๊ธ์ 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;
'๐ป๐ > ๊ฐ๋ฐ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[TS] ์ ํธ๋ฆฌํฐ ํ์ ๋ค (0) | 2022.10.09 |
---|---|
[React] ๋๋ํ๊ฒ useMemo ์ฌ์ฉํ๊ธฐ (0) | 2022.10.09 |
[React] ๋๋ํ๊ฒ useCallback ์ฌ์ฉํ๊ธฐ (0) | 2022.10.02 |
[TS] ๋น ๊ฐ์ฒด์ ๋ํ ์ฌ๋ฐ๋ฅธ ํ์ (0) | 2022.09.03 |
[react-youtube] videoId์ ๋ฐ๋ผ ์์์ด ๋ณ๊ฒฝ๋์ง ์์ ๋ (0) | 2022.09.02 |