JavaScript · Junior · Question 39 of 75

Why is textContent safer than innerHTML for displaying user text?

Explanation

el.innerHTML = userInput parses the string as markup, and <img src=x onerror=alert(1)> runs a script. textContent shows tags as text. If you really need HTML, clean it with a sanitizer (DOMPurify).

Further reading

Problem with a question

JavaScript · Junior · question 39

Test yourself

Take the JavaScript · Junior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz