jQuery interview question · Most asked
What is the difference between .html() and .text(), and why does it matter for security?
Summary
.html(value) parses the value as HTML and inserts the resulting elements; .text(value) inserts it as plain text, escaping < and &. Passing user-controlled data to .html() (or .append(), .prepend(), .after() with an HTML string, or $(htmlString)) creates cross-site scripting vulnerabilities.
Longer Answer
A product review containing <img src=x onerror="stealCookies()"> executes when inserted with .html(). Use .text() for user data, build elements with $("<li>").text(name), and set attributes with .attr() / .prop(). When you must render user-provided HTML (rich text), sanitise it with an allow-list library such as DOMPurify first.
Code Example
// Unsafe: item.name could contain markup
$list.append("<li>" + item.name + "</li>");
// Safe
$("<li>").text(item.name).appendTo($list);
Key Points
.html()parses HTML;.text()escapes.- User data into .html()/.append() strings = XSS.
- Build elements with .text()/.attr().
- Sanitise rich text with DOMPurify.
Deep dive: Code Clinic: review a jQuery shopping cart script
More most-asked jQuery questions
- How do you make AJAX requests with jQuery?
- What is the difference between $(document).ready(), $(fn), DOMContentLoaded and window.onload?
- What is event delegation, and why is it useful?
- How do you bind and unbind events in modern jQuery? What happened to bind, live and delegate?
- What is the difference between .attr() and .prop()?
- What are jQuery Deferreds, and how do you wait for several requests?
- What is the difference between preventDefault(), stopPropagation() and returning false in a jQuery handler?
- What is jQuery, and is it still relevant today?