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<>becomes>&becomes&
Example: <div>User said: <script>alert(1)</script></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"and'becomes'
Example: <input value="User's "input" 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 hrefwithjavascript:protocol: User data becomes executable codesrcattributes: 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.