HTML Attributes

Attributes provide extra information about elements. They appear inside the start tag as name="value" pairs.

  • Most attributes have the form name="value" (quotes recommended).
  • Boolean attributes (like disabled) are true when present.
  • Some attributes are global and can be used on any element (e.g., id, class, style, title).

1) Basic Attribute Usage


<a href="https://codingwithsonu.com" target="_blank">Visit CWS</a>

<img src="../asset/img/sample.jpg" alt="Sample image" width="300">

Common Global Attributes

AttributePurposeExample
id Unique identifier (per page) <div id="hero">...</div>
class Reusable style hook <p class="intro lead">...</p>
style Inline CSS (avoid in production) <span style="color:#f60">Hi</span>
title Tooltip / advisory text <abbr title="HyperText Markup Language">HTML</abbr>
hidden Hide element (not displayed) <div hidden>Secret</div>
lang Language of element content <p lang="hi">नमस्ते</p>
data-* Custom data attributes <li data-id="42" data-role="tag">Item</li>
draggable Enable drag-and-drop (true/false) <img draggable="true">

2) Boolean Attributes


<input type="checkbox" checked>
<button disabled>Can't click</button>
<video autoplay muted loop></video>

Presence = true. You don’t need = "true".

3) Useful Form Attributes


<input type="text" name="user" placeholder="Username" required maxlength="20">

<input type="password" name="pwd" minlength="8" pattern="(?=.*[0-9])(?=.*[a-z]).*">

<input type="number" name="age" min="1" max="120" step="1">

<select name="country" required>
  <option value="">--Select--</option>
  <option value="in">India</option>
</select>

4) Link & Image Attributes


<!-- Links -->
<a href="docs/guide.pdf" download target="_blank" 
   rel="noopener">Download Guide</a>

<!-- Images -->
<img src="../asset/img/sample.jpg" alt="Mountains at sunset" 
     width="400" height="250" loading="lazy">

rel="noopener" (or noreferrer) is recommended with target="_blank" for security.

5) data-* Attributes (Custom Data)


<button id="buyBtn" data-product-id="SKU-101" data-price="499">
  Buy Now
</button>

<script>
  var btn = document.getElementById('buyBtn');
  console.log(btn.dataset.productId, btn.dataset.price); // "SKU-101", "499"
</script>

6) Accessibility: ARIA & role


<nav aria-label="Main navigation">...</nav>
<button aria-expanded="false" aria-controls="menu">Menu</button>
<ul id="menu" role="menu">...</ul>

ARIA helps assistive technologies understand your UI state and relationships.

Best Practices:

  • Always include alt on images for accessibility and SEO.
  • Prefer semantic HTML; use ARIA when native semantics aren’t enough.
  • Don’t misuse attributes (e.g., avoid inline style in production CSS).
  • Validate forms with proper attributes: required, pattern, min/max.
  • Use rel="noopener" with target="_blank" links.