HTML Attributes: Add Information to Elements
Learn HTML attribute syntax with examples of href, src, alt, id, class and boolean attributes.
Write an attribute
Attributes provide additional information about an element. They are written in the opening tag as a name and, for many attributes, a value.
<a href="https://example.com/">Visit the example site</a>
Quote attribute values, especially when they contain spaces. Quoted values are consistent and easy to read.
Common attributes
hrefgives a link its destination.srcidentifies a resource such as an image file.altprovides alternative text for an image. Use an empty value for decorative images.idgives an element a unique identifier in the document.classassigns one or more reusable class names.
<img src="images/flower.jpg" alt="Pink flower in a garden">
<button type="button" disabled>Unavailable</button>
Boolean attributes
A boolean attribute is true when it is present. For example, adding disabled disables a form control; leaving it out means the control is not disabled by that attribute.
<input type="email" required>
<button type="button" disabled>Unavailable</button>
For a boolean attribute, presence is what matters. Writing disabled="false" still leaves the attribute present, so the control remains disabled. Remove the attribute when you want the control enabled.
Global and element-specific attributes
Global attributes such as id, class, lang and title can be used on most HTML elements. Other attributes belong to particular elements: href is used on links, while src and alt are used on images. An attribute only works as intended when the element supports it.
Use classes, IDs and custom data
An element can have several class names separated by spaces. Use classes for styles or groups of elements. An id should identify one element on the page and can also be used as a link destination. Custom data-* attributes can store small values for scripts to read through an element's dataset.
<button class="button button-primary" id="save-button"
data-action="save">Save</button>
<script>
const button = document.querySelector("#save-button");
console.log(button.dataset.action); // "save"
</script>
Do not put private information in a data-* attribute: it is visible in the page source and browser tools. Keep CSS classes and IDs descriptive so the purpose of the markup is easy to understand.
For a full reference, see MDN's HTML global attributes documentation.