Explain Codes LogoExplain Codes Logo

How to show <div> tag literally in <code>/<pre> tag?

html
html-entities
syntax-highlighting
xss
Anton ShumikhinbyAnton Shumikhin·Aug 15, 2024
TLDR

Employ the power of HTML entities! Use &lt; for < and &gt; for >, to display <div> in its text form.

Example:

<code>&lt;div&gt;Content&lt;/div&gt;</code>

This code displays as text: <div>Content</div>.

Alternative methods to display HTML tags

Using a readonly textarea

When working with HTML tags, a readonly textarea can be your best friend.

<textarea readonly> <!-- This readonly textarea is like my stomach after thanksgiving, no more space for input! 😂🍽️ --> &lt;div&gt;Your content&lt;/div&gt;</textarea>

The above code renders as a box showing <div>Your content</div>. Consider it a read-only showcase. But remember, it doesn't offer the spice of syntax highlighting.

The good old xmp tag

Though it smells like your grandpa's records, the <xmp> tag can still do wonders:

<xmp> <!-- This old buddy doesn't understand jokes (or syntaxes)! 😉 --> <div>Content</div></xmp>

However, brushing the dust off this deprecated tag is not recommended due to possible browser interpretation hiccups.

Tips & tricks for displaying HTML tags

Handy entity escaping tools

Online tools, often the unsung heroes, can simplify your life by converting characters into HTML entities, particularly for long or unpredictable code snippets.

Syntax highlighters

Beautify your code by integrating JavaScript libraries like Prism.js or Highlight.js which offer syntax highlighting, while preserving your <div>'s textual form.

HTML sanitation

When you're dealing with user-generated content, HTML sanitization is crucial in safeguarding against XSS attacks. Libraries like DOMPurify can handle this, while demonstrating how to properly display HTML entities.