innerHTML vs textContent
JavaScriptThe short answer
innerHTML gets or sets the HTML content of an element, including any HTML tags. textContent gets or sets only the text, stripping out all HTML tags. The biggest difference is security — innerHTML can execute scripts and create XSS vulnerabilities, while textContent is safe because it treats everything as plain text.
innerHTML
innerHTML returns the full HTML markup inside an element:
const div = document.querySelector('#content');// <div id="content"><strong>Hello</strong> world</div>console.log(div.innerHTML); // "<strong>Hello</strong> world"// Setting innerHTML parses and renders HTMLdiv.innerHTML = '<em>New content</em>';// Now the div contains: <em>New content</em>When you set innerHTML, the browser parses the string as HTML and creates DOM elements.
textContent
textContent returns only the text, ignoring all HTML tags:
const div = document.querySelector('#content');// <div id="content"><strong>Hello</strong> world</div>console.log(div.textContent); // "Hello world"// Setting textContent treats everything as plain textdiv.textContent = '<em>New content</em>';// Now the div shows the literal text: <em>New content</em>When you set textContent, the browser does not parse HTML. It inserts the string as plain text.
Security
This is the most important difference. innerHTML can create XSS (Cross-Site Scripting) vulnerabilities:
// Dangerous! If userInput contains malicious HTML, it will executeelement.innerHTML = userInput;// Safe — treats everything as textelement.textContent = userInput;If userInput is <img src="x" onerror="alert('hacked')">, using innerHTML would execute the JavaScript. Using textContent would just display the text literally.
Rule: Always use textContent when displaying user-generated content.
Performance
textContent is faster than innerHTML because it does not need to parse HTML. If you only need to set or read text, use textContent.
Interview Tip
The key point interviewers want to hear is the security difference. Show that you know innerHTML is dangerous with user input and textContent is safe. If you can give the XSS example, it shows you think about security.
Why interviewers ask this
This question tests basic DOM knowledge and security awareness. Interviewers want to see if you know when to use each one and, more importantly, if you understand the security risk of innerHTML with untrusted data.