Chapter 04 of 26

Elements & Attributes

In HTML Document Structure we saw the skeleton of a page: html, head and body. Everything inside that skeleton is made from just two building blocks: elements and attributes. Learn the rules for these two properly, and you can read and write any HTML element — even ones you have never seen before.

In this chapter we'll learn the exact difference between a tag and an element, how nesting works, what void elements are, how attributes are written, the tricky boolean attributes, the global attributes that work on every element, and HTML comments.


Tags vs Elements

People often use "tag" and "element" as if they mean the same thing. In interviews, it helps to be precise.

A tag is the markup written in angle brackets, such as <p> (start tag) or </p> (end tag).
An element is the complete unit: the start tag, its content, and the end tag together. It becomes one node in the DOM tree.

            element
 ┌─────────────────────────────────────┐
 <p class="note">Hello, students!</p>
 └──────┬───────┘└──────┬───────┘└─┬┘
    start tag        content     end tag
       │
       └── contains an attribute:  class="note"
                                   name   value
  • The start tag has the element name between < and >, and may contain attributes.
  • The end tag has a forward slash before the name: </p>. It never contains attributes.
  • The content can be text, other elements, or both.

Nesting Elements

Elements can contain other elements. This is called nesting, and it is what builds the DOM tree.

<p>This paragraph has <strong>bold <em>and italic</em></strong> text nested inside it.</p>

Output:

This paragraph has bold and italic text nested inside it.
                   ^^^^ ^^^^^^^^^^
                   bold  bold + italic

The tree for this paragraph:

p
├── "This paragraph has "
├── strong
│   ├── "bold "
│   └── em
│       └── "and italic"
└── " text nested inside it."

The nesting rule: last opened, first closed

Elements must be closed in the reverse order in which they were opened. If you have studied data structures, this is exactly the behaviour of a stack (LIFO): the most recently opened element must be closed first.

<!-- Correct: em was opened last, so it is closed first -->
<p><strong><em>Right order</em></strong></p>

<!-- Wrong: tags overlap instead of nesting -->
<p><strong><em>Wrong order</strong></em></p>

What does the browser do with the wrong version? We loaded it in Chrome and checked the DOM:

<p><strong><em>Wrong order</em></strong></p>

The browser's error-recovery rules silently repaired it. In this simple case the result looks fine, but in bigger pages overlapping tags can cause the browser to duplicate or move elements in ways you didn't expect — and a validator will flag it. Always nest correctly.

This "stack" idea is a classic interview programming question too: "Write a function to check whether the tags in an HTML string are properly nested" — the solution is the same as checking balanced brackets with a stack.


Void (Empty) Elements

Some elements cannot have any content, so they have only a start tag and no end tag. These are called void elements.

<br>
<hr>
<img src="logo.png" alt="CS Learning Portal logo">
<input type="text">
<meta charset="utf-8">

The complete list in the current HTML standard:

Void elementPurpose
areaClickable area inside an image map
baseBase URL for relative links (in head)
brLine break
colTable column
embedEmbedded external content
hrThematic break
imgImage
inputForm input
linkLink to an external resource such as a stylesheet
metaMetadata
sourceMedia source for picture/audio/video
trackSubtitles/captions for video
wbrOptional line-break opportunity

(You may see <param> in old lists. It was used to pass parameters to browser plugins through <object>; it has since been removed from the standard and is now obsolete, so don't use it.)

What about <br />?

You will often see void elements written with a slash, like <br /> or <img … />. This style comes from XHTML and is also required in JSX (React). In HTML:

  • On a void element, the trailing slash is allowed but ignored. <br> and <br /> are identical.
  • On a normal element, the slash does nothing — HTML has no "self-closing" tags. We tested <div/>Some text in Chrome: the browser treated it as an open <div>, and "Some text" plus everything after it ended up inside that div.
  • Void elements must never have an end tag: <br></br> and <input></input> are errors.

Optional end tags

Some normal elements, like <p> and <li>, have end tags that the standard allows you to omit, because the parser can work out where they end. Just like with html/head/body in the previous chapter, the recommended practice is: always write the end tag for clarity.


Case Sensitivity

HTML element and attribute names are case-insensitive. We tested:

<P CLASS="Note" ID="Intro">Upper case tags</P>

Chrome's DOM:

<p class="Note" id="Intro">Upper case tags</p>

Notice two things: the names were converted to lowercase, but the values Note and Intro kept their capital letters. Attribute values like id and class are case-sensitive: in our test, document.getElementById("box") returned null for an element with id="Box". The universal convention is to write tag and attribute names in lowercase.


Attributes

An attribute provides extra information about an element or changes its behaviour. Attributes are written inside the start tag as name="value" pairs, separated by spaces.

<img src="logo.png" alt="CS Learning Portal logo" width="120" height="40">
AttributeValueMeaning
srclogo.pngWhich image file to load
altCS Learning Portal logoText alternative if the image can't be seen
width, height120, 40Width and height in pixels (written without "px"); also lets the browser reserve space before the image loads

Rules for writing attributes

  • Attributes go only in the start tag.
  • The order of attributes does not matter.
  • The same attribute must not appear twice on one element. If it does, the browser keeps the first one and drops the rest. (We tested <p class="first" class="second"> — the element's class was first.)
  • Values can be in double quotes (most common), single quotes, or even unquoted if they contain no spaces or special characters such as ", ', =, <, > or a backtick.
<p title="double quotes">A</p>
<p title='single quotes'>B</p>
<p title=unquoted>C</p>
<p title='He said "hi"'>D — single quotes let you use " inside</p>

Recommendation: always use double quotes. Unquoted values break as soon as someone adds a space — class=note important would create a class note and a separate, meaningless attribute named important.

Element-specific vs global attributes

Many attributes only make sense on particular elements: href on <a>, src and alt on <img>, type on <input>. We'll learn them with each element. But some attributes, called global attributes, can be used on any element.


Important Global Attributes

AttributePurposeExample
idA unique identifier for one element in the page. Used by links (#id), CSS and JavaScript.id="intro"
classOne or more space-separated class names. Many elements can share a class. Mainly used for CSS and JavaScript.class="note important"
styleInline CSS for this element. Works, but avoid it — keep styles in CSS files.style="color: red"
titleAdvisory text, usually shown as a tooltip on mouse hover. Not reliable on touch screens or for keyboard users, so never put essential info only here.title="Read more"
langLanguage of the element's contentlang="hi"
dirText direction: ltr, rtl or autodir="rtl"
hiddenThe element is not relevant right now, so it is not displayed. Usually written on its own like a boolean attribute (it also accepts the special value until-found)hidden
tabindexControls whether an element can receive keyboard focustabindex="0"
data-*Custom data for your own scripts; name must start with data-data-roll-no="21CS045"
contenteditableLets the user edit the element's text in the pagecontenteditable="true"

id vs class

idclass
Must be unique in the whole documentCan be reused on many elements
An element has at most one idAn element can have many classes: class="card featured"
Can be a link target: page.html#introCannot be a link target
CSS selector: #introCSS selector: .card
Value must not contain spacesSpaces separate different class names

Worked example: global attributes in action

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Global attributes</title>
</head>
<body>
    <p id="intro" class="note important" title="Hover tooltip">Intro paragraph</p>
    <p data-roll-no="21CS045" data-branch="CSE">Student: Ananya</p>
    <p dir="rtl" lang="ar">مرحبا</p>
    <!-- This comment is not displayed -->
    <p contenteditable="true">Click and type here.</p>
</body>
</html>

Output:

Intro paragraph                         (hover → tooltip "Hover tooltip")

Student: Ananya                         (data-* values are invisible)

                                                         مرحبا   ← right-aligned (rtl)

Click and type here.                    (you can click and edit this text)

Notice: id, class and data-* change nothing visually on their own. They are hooks for CSS and JavaScript (for example, a script can read element.dataset.rollNo). The dir="rtl" paragraph is laid out right-to-left, so the Arabic word appears at the right edge.


Boolean Attributes

Some attributes are boolean: their presence means true and their absence means false. Examples: disabled, checked, selected, required, readonly, multiple, autofocus.

<label><input type="checkbox" checked> Remember me</label>
<button type="button" disabled>Disabled button</button>
<button type="button">Normal button</button>

Output: a ticked checkbox labelled "Remember me", a greyed-out button that can't be clicked, and a normal clickable button.

Valid ways to write a boolean attribute:

<button type="button" disabled>OK</button>              <!-- most common -->
<button type="button" disabled="">OK</button>
<button type="button" disabled="disabled">OK</button>

The classic trap: disabled="false"

What does this do?

<button type="button" disabled="false">Click</button>

Many beginners expect an enabled button. But the browser only checks whether the attribute is present. We tested it: the button's disabled property was true — the button was disabled. (The value "false" is also invalid HTML.) To make it enabled, remove the attribute completely.

This trips people up again in JavaScript and React, so remember it: for boolean attributes, presence = true.


HTML Comments

Comments are notes for developers. The browser ignores them when rendering.

<!-- Navigation starts here -->
<p>Visible text</p>

<!--
    Multi-line comments
    are fine too.
-->
  • A comment starts with <!-- and ends at the first -->. Therefore comments cannot be nested.
  • Comments are not secret. Anyone can read them with View Source. Never put passwords, API keys or private notes in them.
  • Useful for temporarily "switching off" a piece of markup while testing.

Putting It All Together

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Elements and Attributes</title>
</head>
<body>
    <h1 id="top" title="This text appears as a tooltip">Elements &amp; Attributes</h1>
    <p>This paragraph has <strong>bold <em>and italic</em></strong> text nested inside it.</p>
    <p lang="hi">यह पैराग्राफ हिंदी में है।</p>
    <p hidden>You will not see this paragraph.</p>
    <img src="logo.png" alt="CS Learning Portal logo" width="120" height="40">
    <p>
        <label><input type="checkbox" checked> Remember me</label>
        <button type="button" disabled>Disabled button</button>
        <button type="button">Normal button</button>
    </p>
    <hr>
    <p>A line<br>break</p>
</body>
</html>

Output (when logo.png does not exist in the folder):

Elements & Attributes                       ← heading; hover shows tooltip

This paragraph has bold and italic text nested inside it.

यह पैराग्राफ हिंदी में है।

[broken-image icon] CS Learning Portal logo   ← alt text shown because the file is missing

[✓] Remember me  [Disabled button]  [Normal button]
──────────────────────────────────────────────────
A line
break

Points to observe:

  • We wrote &amp; in the heading to display an & character. Characters like < and & have special meaning in HTML; this is covered in Character Entities & Symbols.
  • The hidden paragraph does not appear at all.
  • Because logo.png is missing, the browser shows a broken-image icon with the alt text — exactly why alt matters.
  • <br> and <hr> are void elements; we'll use them properly in the next chapter.

Common Mistakes

MistakeWhy it's wrongCorrect
<b><i>text</b></i>Overlapping instead of nesting<b><i>text</i></b>
<br></br>Void elements have no end tag<br>
<div /> expecting an empty divThe slash is ignored; the div stays open<div></div>
Same id on two elementsids must be unique; scripts and links find only oneUse a class for repeated styling
disabled="false"Boolean attribute is still present → trueRemove the attribute
Attribute in the end tag: </p class="x">End tags can't have attributesPut it in the start tag
class=note importantUnquoted value stops at the spaceclass="note important"
id="Box" but script looks for "box"id/class values are case-sensitiveUse consistent lowercase names

Interview / Exam Questions

1. What is the difference between an HTML tag and an HTML element?

A tag is the markup in angle brackets, such as <p> or </p>. An element is the whole structure — start tag, content and end tag — which becomes a node in the DOM. Void elements consist of only a start tag.

2. What are void elements? Give five examples.

Elements that cannot have content and therefore have no end tag. Examples: br, hr, img, input, meta, link, source, wbr.

3. Is <br /> correct in HTML? Does <div /> create an empty div?

<br /> is allowed; the slash is ignored on void elements. <div /> does not create an empty div — HTML has no self-closing syntax for normal elements, so the div stays open until it's closed or the parser closes it.

4. What is a boolean attribute? What does <input disabled="false"> do?

A boolean attribute is true when present and false when absent. disabled="false" still disables the input because the attribute is present; to enable it you must remove the attribute.

5. Difference between id and class?

id uniquely identifies one element (and can be a link fragment target); class can be shared by many elements and an element can have multiple classes. In CSS, #name selects by id and .name by class.

6. What are data-* attributes used for?

They store custom, private data on elements for use by the page's own scripts, e.g. data-product-id="42", read in JavaScript as element.dataset.productId. They have no visual effect.

7. Are HTML tags case-sensitive?

Element and attribute names are not case-sensitive (the parser lowercases them), but many attribute values — like id and class — are case-sensitive. Lowercase names are the convention.


Summary

  • A tag is markup in angle brackets; an element is start tag + content + end tag.
  • Elements must be nested properly — last opened, first closed (like a stack).
  • Void elements (br, hr, img, input, meta, link…) have no end tag; HTML has no self-closing tags for other elements.
  • Attributes go in the start tag as name="value"; always use double quotes, never repeat an attribute.
  • Global attributes like id, class, title, lang, hidden and data-* work on any element.
  • Boolean attributes are true when present — disabled="false" is still disabled.
  • Comments (<!-- -->) are invisible on the page but visible in the source.

Next, in Headings & Paragraphs, we start using real content elements and learn how browsers treat whitespace and line breaks.