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

← All jQuery questions