Interview question
What is the difference between innerHTML, innerText, and textContent? innerHTML, innerText, और textContent में क्या अंतर है?
Answer
| Property | Parses HTML? | Respects CSS visibility? | Performance |
|---|---|---|---|
| innerHTML | Yes - renders tags as elements | N/A (sets raw markup) | Slower, triggers reflow/reparse |
| innerText | No - plain text only | Yes - ignores hidden elements, aware of CSS | Slower - triggers layout/reflow to compute visible text |
| textContent | No - plain text only | No - includes hidden text too | Fastest - no layout calculation needed |
// HTML: <div id='box'>Hello <span style='display:none'>Hidden</span> World</div>
const box = document.getElementById('box');
console.log(box.innerHTML); // 'Hello <span style="display:none">Hidden</span> World'
console.log(box.innerText); // 'Hello World' - skips hidden text
console.log(box.textContent); // 'Hello Hidden World' - includes hidden text
// Setting values
box.innerHTML = '<strong>Bold</strong>'; // renders as bold text
box.textContent = '<strong>Bold</strong>'; // renders literally as the string '<strong>Bold</strong>'
// XSS risk with innerHTML and user input
const userInput = '<img src=x onerror="alert(1)">';
box.innerHTML = userInput; // DANGEROUS - executes the script
box.textContent = userInput; // SAFE - displays as plain text
// Performance tip: use textContent when you don't need to parse HTML
// and don't need to account for visibility (most common case for plain text)| Property | HTML parse करता है? | CSS visibility respect? | Performance |
|---|---|---|---|
| innerHTML | हाँ | N/A | धीमा |
| innerText | नहीं | हाँ - hidden elements ignore | धीमा |
| textContent | नहीं | नहीं | सबसे तेज़ |
const box = document.getElementById('box');
console.log(box.innerHTML); // HTML tags सहित
console.log(box.innerText); // hidden text छोड़ देता है
console.log(box.textContent); // hidden text सहित सब कुछ
box.innerHTML = '<strong>Bold</strong>'; // bold render होगा
box.textContent = '<strong>Bold</strong>'; // literal string दिखेगा
// innerHTML से XSS risk
const userInput = '<img src=x onerror="alert(1)">';
box.innerHTML = userInput; // खतरनाक
box.textContent = userInput; // सुरक्षितWas this answer clear?