
๐ javascript ๋ฅผ ์๊ฒ๋์ง, ๋ฒ์จ 2์ฃผ๋ผ๋ ์๊ฐ์ด ํ๋ ๋๋ฐ์, 2์ฃผ ๋์ ์์ ๋ฅผ ๋ณด๋ฉด์ innerHTML, innerText, textContent๋ฅผ ํ๋ฒ์ฉ์ ์จ๋ณธ ๊ฒ ๊ฐ์ต๋๋ค. ๊ทธ๋๋ ์ฐจ์ด์ ์ ๋ํด ์์๋ณด๋ ค ํ์ง๋ง, ์ด์ฉ๋ค ๋ณด๋..์ ๋ชฉ๋ง ์ ์ด๋๊ณ ์์์ ์ฅ ํ ์ด ๊ธ์ ๋ง๋ฌด๋ฆฌ ํ ๊น ํฉ๋๋ค.
๊ทธ๋ผ ์ด๋ฒ ํฌ์คํ ์ ์ฃผ์ ๋ innerHTML, innerText, textContent์ ์ฐจ์ด์ ์ ๋ํด์ ์ ๋ฆฌํด๋ณด๊ฒ ์ต๋๋ค.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>example</title> </head> <body> <div id="example">Hello <span>world!</span></div> </body> <script> const text = document.getElementById('example'); /* alert(test.innerHTML); // Hello <span>world!</span> alert(text.innertext); // Hello world! alert(text.textContent); //Hello world! */ </script> </html>
<body> <div id="example"></div> </body> <script> const test = document.getElementById('example'); test.innerHTML = "<div style = 'color:red'>test</div>" </script> </html>๊ฒฐ๊ณผ
<script> const test = document.getElementById('example'); test.innerText = "<div style = 'color:red'>test</div>" // textContent ๋ innerText ์ ๊ฒฐ๊ณผ๊ฐ ๊ฐ๋ค. </script>๊ฒฐ๊ณผ
์์ ๊ฒฐ๊ณผ๋ง ๋ณด๋๋ผ๋, innerHTML ์ ๋ค๋ฅธ ๊ฒ๋ค๊ณผ ๋ฌ๋ฆฌ HTML ์ ๋ฐํํ๊ณ ์๋ ๊ฒ์ ๋ณผ์์๋ค.
โ ๊ทธ๋ผ innerText์ textContent ์ ์ฐจ์ด์ ์ ๋ฌด์์ผ๊น?
innerText๋ CSS์ ์์ข
์ ์ธ๋ฐ, ์๋ฅผ ๋ค์ด display:none; ์ผ๋ก ์ง์ ๋ ์์ ๋
ธ๋์ ํ
์คํธ๋ ๋ฐํํ์ง ์๋๋ค. ๊ทธ๋ ๊ธฐ ๋๋ฌธ์ innerText ๋ CSS๋ฅผ ๊ณ ๋ คํด์ผ ํ๋ฏ๋ก textContent ๋ณด๋ค ๋๋ฆฌ๋ค๋ ๋จ์ ์ด ์๋ค.