Course contentsShow
← Security
Lesson 1221 of 3,05225. Application Security - Secure CodingFree lesson

HTML Entity Encoding and Attribute Context

Mastering HTML encoding for element content versus attribute values and understanding special attribute contexts.

What You'll Learn

You'll learn how to apply HTML entity encoding correctly in both element content and attribute values, and why certain attributes demand extra care.

The Core Problem: One Encoding Doesn't Fit All

When you learned about context-specific output encoding, you discovered that different parts of an HTML document need different encoding strategies. HTML entity encoding itself comes in two flavors depending on where your data appears:

Element Content Encoding

When inserting user data between HTML tags (element content), you must encode characters that have special meaning in HTML:

  • < becomes &lt;
  • > becomes &gt;
  • & becomes &amp;

Example: <div>User said: &lt;script&gt;alert(1)&lt;/script&gt;</div>

This prevents the browser from interpreting user input as HTML structure.

Attribute Value Encoding

Inside HTML attributes, you face additional risks. You must encode:

  • All the above characters, plus
  • Quotes: " becomes &quot; and ' becomes &#x27;

Example: <input value="User's &quot;input&quot; here">

Special Attribute Contexts: The Danger Zone

Some attributes accept executable content and are inherently dangerous for untrusted data:

  • JavaScript event handlers: onclick, onerror, onload — Never put user input here; requires JavaScript encoding if unavoidable
  • href with javascript: protocol: User data becomes executable code
  • src attributes: Can load remote resources or execute JavaScript

Analogy: Element encoding is like locking your front door. Attribute encoding is like locking both the front door and the windows. Special executable attributes are like leaving your safe wide open—avoid putting untrusted data there at all.

Testing Your Understanding

Can you spot the vulnerability? <a href="javascript:navigate('USER_INPUT')"> — Even with HTML encoding, the user input sits inside a JavaScript context within an attribute!

Key Takeaway: HTML entity encoding must match the context—element content needs basic escaping, attributes need quote escaping too, and executable attributes should never contain untrusted data without JavaScript-specific encoding or, better yet, architectural redesign to avoid them entirely.