x-text Directive

Set text content safely – escapes HTML automatically to prevent XSS.

What is x-text?

x-text sets the textContent of an element. It's safe because it automatically escapes HTML entities, preventing XSS attacks. This is the go‑to directive for displaying dynamic text.

When to Use

Use x-text whenever you need to display text that comes from user input or an API. It’s perfect for showing names, messages, or any variable string.

Example

Code
<div x-data="{ message: 'Hello <b>World</b>' }">
  <span x-text="message"></span>
  <!-- Output: Hello <b>World</b> (as plain text) -->
</div>

If you need to render HTML (e.g., from a trusted CMS), use x-html with extreme caution.

Does x-text prevent XSS attacks?

Yes, because it sets textContent, not innerHTML. All special characters are escaped.

Helpful? Share this page!↑ Back to top