insertAdjacentHTML
1. ๊ฐ์
์์๋ฅผ ์ถ๊ฐํ๊ธฐ ์ํด innerHTML
ํ๋กํผํฐ๋ฅผ ์ฌ์ฉํ๋ฉด ๊ธฐ์กด ์์๋ฅผ ๋ชจ๋ ์ ๊ฑฐํ ํ ์๋กญ๊ฒ ์์ฑ์ด ๋๋ค. ์ด๋ ๋นํจ์จ์ ์ด๋ผ ํ ์ ์๋ค. ์ด๋ฅผ ํด๊ฒฐํ ์ ์๋ insertAdjacentHTML
๋ฉ์๋๋ฅผ ์์๋ณด์.
2. insertAdjacentHTML
insertAdjacentHTML(position, DOMString)
๋ฉ์๋๋ ๊ธฐ์กด ์์๋ฅผ ์ ๊ฑฐํ์ง ์์ผ๋ฉด์ ์์น๋ฅผ ์ง์ ํด ์๋ก์ด ์์๋ฅผ ์ฝ์
ํ๋ค.
์ฒซ ๋ฒ์งธ ์ธ์๋ก ์ ๋ฌํ ์ ์๋ ๋ฌธ์์ด์ beforebegin
, afterbegin
, beforeend
, afterend
์ 4๊ฐ์ง์ด๋ค.

2-1. insertAdjacentHTML - beforebegin
<!DOCTYPE html>
<html lang="en">
<body>
<div id="foo">
Hello
<div>world</div>
</div>
<script>
const $foo = document.getElementById("foo");
$foo.insertAdjacentHTML("beforebegin", "<div> beforebegin insert</div>");
</script>
</body>
</html>

2-2. insertAdjacentHTML - afterbegin
<!DOCTYPE html>
<html lang="en">
<body>
<div id="foo">
Hello
<div>world</div>
</div>
<script>
const $foo = document.getElementById("foo");
$foo.insertAdjacentHTML("afterbegin", "<div> afterbegin insert</div>");
</script>
</body>
</html>

2-3. insertAdjacentHTML - beforeend
<!DOCTYPE html>
<html lang="en">
<body>
<div id="foo">
Hello
<div>world</div>
</div>
<script>
const $foo = document.getElementById("foo");
$foo.insertAdjacentHTML("beforeend", "<div> beforeend insert</div>");
</script>
</body>
</html>

2-4. insertAdjacentHTML - afterend
<!DOCTYPE html>
<html lang="en">
<body>
<div id="foo">
Hello
<div>world</div>
</div>
<script>
const $foo = document.getElementById("foo");
$foo.insertAdjacentHTML("afterend", "<div> afterend insert</div>");
</script>
</body>
</html>

3. insertAdjacentHTML ์ฅ์ ๊ณผ ๋จ์
insertAdjacentHTML
๋ฉ์๋๋ ๊ธฐ์กด ์์์ ์ํฅ์ ์ฃผ์ง ์๊ณ ์๋กญ๊ฒ ์ฝ์
๋ ์์๋ง ํ์ฑํ์ฌ ์์ ์์๋ก ์ถ๊ฐํ๋ค๋ ๊ฒ์ด๋ค. ์ด๋ innerHTML
ํ๋กํผํฐ๋ณด๋ค ํจ์จ์ ์ด๊ณ ๋น ๋ฅด๋ค.
ํ์ง๋ง innerHTML
ํ๋กํผํฐ์ ๋ง์ฐฌ๊ฐ์ง๋ก HTML ๋งํฌ์
๋ฌธ์์ด์ ํ์ฑํ๋ฏ๋ก ํฌ๋ก์ค ์ฌ์ดํธ ์คํฌ๋ฆฝํ
๊ณต๊ฒฉ์ ์ทจ์ฝํ๋ค.
4. Conclusion
insertAdjacentHTML
๋ฉ์๋๋ ์์ง ์ฌ์ฉํด ๋ณธ ์ ์ด ์๋ ๋ฉ์๋์ด๋ค.innerHTML
ํ๋กํผํฐ๋ง ์ฌ์ฉ์ ํด๋ณด์๋ค. ์์ผ๋ก๋ ๋ ํจ์จ์ ์ธinsertAdjacentHTML
๋ฉ์๋๋ฅผ ์ฌ์ฉํด๋ณด๋๋ก ํ์. ๋ํ ์์น๊น์ง ์ ํ ์ ์์ผ๋ ํ์ฉํ ์ ์๋ ๋ฐฉ์ ๋์ฑ ๋ง์ ๊ฒ์ด๋ค.
์ฐธ๊ณ
๋์ - ๋ชจ๋ ์๋ฐ์คํฌ๋ฆฝํธ Deep Dive: ์๋ฐ์คํฌ๋ฆฝํธ์ ๊ธฐ๋ณธ ๊ฐ๋ ๊ณผ ๋์ ์๋ฆฌ
๐ 2022-10-15
Last updated