midjQuery
What is the difference between .html(), .text(), and .val() in jQuery?
Updated May 14, 2026
Short answer
.html() manipulates HTML content, .text() works with plain text, and .val() handles form input values.
Deep explanation
These three methods are frequently used for content manipulation in jQuery, but they serve different purposes.
- .html()
- Retrieves or sets HTML content inside an element.
- Parses HTML tags.
- Can inject markup dynamically.
- .text()
- Retrieves or sets plain textual content.
- Escapes HTML automatically.
- Safer when handling user-generated content.
- .val()
- Retrieves or sets values of form elements.
- Commonly used with input, textarea, and select elements.
Security consideration: Using .html() with unsanitized user input may introduce Cross-Site Scripting (XSS) vulnerabilities. Modern best practice recommends sanitizing content before inserting HTML dynamically.
Performance consideration: .text() is generally faster than .html() because it does not parse HTML structures.
Real-world example
A chat application may use .text() to safely render user messages while an admin dashboard might use .html() to dynamically inject formatted reports and widgets.
Common mistakes
- Using .html() with user-generated content without sanitization can create severe security vulnerabilities such as XSS attacks.
Follow-up questions
- Why is .text() safer than .html()?
- Can .val() work on non-form elements?
- When should .html() be preferred?