Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / HTML

HTML element: code

The code element identifies a fragment recognized by a computer, such as an element name, command, filename, or program statement.

Version: WHATWG HTML Living Standard; index snapshot date recorded separately

Syntax

<pre><code>&lt;button>Save&lt;/button></code></pre>

code gives a fragment meaning but does not preserve indentation and line breaks by itself; a multiline listing normally uses a parent pre.

In literal code text, < and & must be escaped as &lt; and &amp; where needed; > generally need not be escaped. code semantics create no inert parsing boundary: an unescaped button becomes an element, and nested executable HTML remains active.

code does not declare a programming language. A class such as class="language-js" is a tool convention, while lang describes natural language under HTML rules.

Use kbd for user input, samp for program output, and var for a variable. The example reads textContent and uses querySelectorAll() to confirm there is no active button.

Examples

<!doctype html>
<meta charset="utf-8">
<pre id="sample"><code id="snippet">&lt;button type="button">Save&lt;/button>
const ready = left &lt; right &amp;&amp; enabled;</code></pre>
<output id="result"></output>
<script>
const snippet = document.querySelector("#snippet");
const lines = snippet.textContent.split("\n");
document.querySelector("#result").textContent = `lines=${lines.length}; first=${lines[0]}; second=${lines[1]} buttons=${snippet.querySelectorAll("button").length}; parent=${snippet.parentElement.tagName}`;
</script>

Result

lines=2; first=<button type="button">Save</button>; second=const ready = left < right && enabled; buttons=0; parent=PRE

The result verifies two preserved lines, literal markup, and a PRE parent; it neither executes nor syntax-highlights the sample.

Sources