Contents

Frontend Development › HTML

Attribute

Extra information on an element, like href or alt.

Also known as: HTML attributes, attribute, href, alt

An attribute is extra information inside an HTML element’s opening tag, written as name="value".

<a href="/pricing" target="_blank" rel="noopener">Pricing</a>
<img src="kettle.webp" alt="A steel kettle" width="400" height="300">
<input type="email" name="email" required>
<div id="cart" class="panel highlighted" hidden>...</div>

Common ones

AttributeUsed onPurpose
idanya unique identifier, for links and scripts
classanyone or more names for styling and selection
href<a>, <link>where a link goes
src<img>, <script>the file to load
alt<img>a text alternative (alt text)
type, name, value<input>what kind of field it is, and what’s submitted (forms)
placeholder, required, disabledform fieldshints and behavior
styleanyinline CSS (use classes instead)
data-*anyyour own data (data attributes)
aria-*, roleanyaccessibility (ARIA)

Boolean attributes

Some attributes are on or off, and only their presence matters:

<button disabled>Save</button>       <!-- disabled="false" would STILL be disabled -->

To turn it off, remove the attribute (in JavaScript, button.disabled = false or removeAttribute).

Working with them in JavaScript

link.getAttribute("href");
link.setAttribute("href", "/new");
link.hasAttribute("target");
link.removeAttribute("target");

Many attributes are also available as properties (img.src, input.value), though attribute and property can differ (an input’s current value vs its original value attribute).

Tips

  • Always use quotes around values.
  • id values must be unique on a page.
  • Attribute names are case-insensitive, and conventionally lowercase.
  • Untrusted data put into attributes must be escaped, or it enables XSS (XSS).