Courses / HTML · Advanced

Elements, Tags, Attributes

Self-paced 40 sections 65 people viewed this
html html5 html tutorial learn html web development semantic html html forms html accessibility html seo html interview questions html projects beginner to advanced html

Section 3: HTML Elements, Tags, Attributes and Nesting Rules

Welcome to Section 3 of Codementrix HTML5 Mastery. In this lesson, you will learn how HTML elements are constructed, how tags and attributes work, how to nest elements correctly, and how to avoid common markup errors. These concepts are essential for building maintainable, accessible web pages.


1. Learning Objectives

By the end of this lesson, you will be able to:

  • Explain the difference between an HTML element, tag, and attribute.
  • Identify opening tags, closing tags, and void elements.
  • Write HTML elements with correctly formatted attributes.
  • Use quoted attribute values and understand Boolean attributes.
  • Apply proper nesting and closing-tag rules.
  • Recognize elements that cannot contain certain other elements.
  • Understand parent, child, sibling, and descendant relationships.
  • Debug malformed HTML using a browser and an HTML validator.

2. What Is an HTML Element?

An HTML element represents a component of a web page, such as a paragraph, heading, link, image, or form control.

Consider this example:

<p>Welcome to Codementrix.</p>

This is a paragraph element. It contains an opening tag, text content, and a closing tag.

  • <p> is the opening tag.
  • Welcome to Codementrix. is the text content.
  • </p> is the closing tag.
  • The complete structure is the paragraph element.

HTML elements can contain text, other HTML elements, or both. Some elements do not have ordinary text content or closing tags; these are called void elements.

Example: Different HTML Elements

<h1>Welcome to My Website</h1>

<p>Learn web development with Codementrix.</p>

<a href="https://example.com">Visit Example</a>

Here, the browser interprets the elements according to HTML rules. The heading identifies a heading, the paragraph identifies a paragraph, and the anchor creates a hyperlink.

Important: HTML describes the structure and meaning of content. CSS controls presentation, while JavaScript can add behavior.


3. HTML Tags vs Elements

The terms tag and element are related, but they do not mean exactly the same thing.

  • Tag: The markup syntax enclosed by angle brackets, such as <h2> or </h2>.
  • Element: The complete HTML construct, including its tags and content where applicable.

For example:

<h2>Our Services</h2>

<h2> and </h2> are tags. The entire heading construct is the element.

Self-Contained Syntax and Void Elements

Some HTML elements are known as void elements. They cannot have child nodes and must not have closing tags in HTML syntax.

<img src="team.jpg" alt="Our development team">
<br>
<hr>
<input type="email" name="email">
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">

Common void elements include:

  • <area>
  • <base>
  • <br>
  • <col>
  • <embed>
  • <hr>
  • <img>
  • <input>
  • <link>
  • <meta>
  • <source>
  • <track>
  • <wbr>

Do not write a closing tag for a void element. For example, use <img src="photo.jpg" alt="A photo">, not <img></img>.

In HTML, a trailing slash is unnecessary for void elements. In addition, a slash does not make a non-void element self-closing. For example, <div /> does not work like a self-closing XML element in HTML.


4. Opening Tags and Closing Tags

Most HTML elements use an opening tag and a closing tag. The closing tag contains a forward slash before the element name.

<strong>Important information</strong>

<em>Emphasized text</em>

<section>
  <h2>About Us</h2>
  <p>We build practical software solutions.</p>
</section>

In the last example, the section element begins with <section> and ends with </section>. The heading and paragraph are inside it.

Are Closing Tags Always Required?

Some non-void HTML elements have optional end tags under specific conditions defined by HTML. For example, a paragraph end tag may be omitted when the HTML rules allow it. However, beginners should generally write explicit closing tags for elements that require them and use clear, consistent markup.

For example, this is clear and recommended:

<p>First paragraph.</p>
<p>Second paragraph.</p>

Do not assume every element can omit its closing tag. Rules depend on the element and its position in the document.


5. HTML Attributes: Adding Information to Elements

Attributes provide additional information or configuration for an HTML element. They are generally written in the opening tag, after the element name.

Example:

<a href="https://codementrix.in" target="_blank" rel="noopener">
  Visit Codementrix
</a>

This example uses three attributes:

  • href specifies the destination of the link.
  • target="_blank" requests that the destination open in a new browsing context, usually a new tab.
  • rel="noopener" prevents the newly opened page from accessing the originating page through window.opener.

The text Visit Codementrix is the link's content, not an attribute.

Attribute Syntax

The usual form is:

<element-name attribute-name="attribute value">Content</element-name>

For example:

<img src="logo.png" alt="Codementrix logo" width="200">

Here, src, alt, and width are attributes. Their values identify the image file, describe the image for users who cannot see it, and specify its displayed width in CSS pixels.

Multiple Attributes

An element can have multiple attributes. Separate attributes with whitespace, usually spaces or line breaks.

<input
  type="email"
  id="work-email"
  name="email"
  placeholder="you@example.com"
  required
>

This input is configured as an email field with an identifier, a form-submission name, placeholder text, and a required constraint.

Attribute order usually does not affect meaning. The following examples are equivalent in their essential behavior:

<input type="text" name="username" id="username">

<input id="username" name="username" type="text">

6. Quoted and Unquoted Attribute Values

HTML allows attribute values to be written with double quotes, single quotes, or without quotes in limited cases. For reliable, readable code, use quotes consistently.

Double Quotes (Recommended)

<a href="https://example.com">Example</a>

Single Quotes

<a href='https://example.com'>Example</a>

Unquoted Values

<input type=text>

An unquoted value is valid only when it is non-empty and contains no ASCII whitespace or any of the characters that make an unquoted value invalid, including quotation marks, apostrophes, equals signs, less-than signs, greater-than signs, and grave accents.

This is invalid because the value contains a space:

<input placeholder=Enter your name>

The browser cannot interpret that as the intended single attribute value. Write:

<input placeholder="Enter your name">

Best practice: Quote all attribute values. It makes markup easier to read, maintain, and debug.


7. Boolean Attributes

Boolean attributes represent true-or-false states through their presence or absence. If a Boolean attribute is present, it is generally considered true, even when its value is an empty string or repeats its own name.

<input type="text" required>

<button disabled>Unavailable</button>

<video controls></video>

<input type="checkbox" checked>

Examples:

  • required indicates that a form control must be completed before successful constraint validation.
  • disabled disables a supported form control or button.
  • controls requests built-in media controls.
  • checked indicates that a checkbox or radio button is initially checked.

These are all valid Boolean-attribute forms in HTML:

<input required>
<input required="">
<input required="required">

Do not write required="false" expecting the attribute to turn off. Because the attribute is present, it is true. To make the field not required, remove the attribute.

Boolean Attributes vs Ordinary Attributes

Do not confuse Boolean attributes with ordinary attributes that accept meaningful text values.

<input type="email" name="email">

type and name have specific values. Writing type="false" does not mean the input type is disabled; it supplies an invalid or unsupported type value, which is handled according to HTML's rules.


8. Global Attributes

Global attributes are attributes that can be used on all HTML elements, although their effects depend on the attribute and element.

Common Global Attributes

  • id — identifies an element with a unique identifier within the document.
  • class — associates an element with one or more classes.
  • title — provides advisory information, often shown as a tooltip by some browsers.
  • lang — identifies the language of an element's content.
  • dir — sets text direction, such as left-to-right or right-to-left.
  • hidden — indicates that the element is not currently relevant and should not be rendered normally.
  • tabindex — controls focusability and sequential keyboard navigation behavior.
  • contenteditable — indicates whether the element's content can be edited by the user.
  • data-* — stores custom data for scripts and application behavior.
  • style — specifies inline CSS declarations.

These attributes will be explored in greater detail in later sections where appropriate.

Example

<article
  id="article-101"
  class="blog-card featured"
  lang="en"
  data-article-id="101"
  title="Read the article summary"
>
  <h2>Learning HTML</h2>
  <p>Start with well-structured markup.</p>
</article>

In this example:

  • id="article-101" provides a document identifier.
  • class="blog-card featured" assigns two classes.
  • lang="en" identifies the language as English.
  • data-article-id="101" stores a custom data value.
  • title supplies advisory information.

Important: An id should be unique in the document. Class names can be reused on multiple elements.


9. Nesting HTML Elements Correctly

Nesting means placing one HTML element inside another. The outer element is the parent, and the inner element is a child.

<section>
  <h2>Our Services</h2>
  <p>We provide <strong>reliable web development</strong> services.</p>
</section>

Relationships in this example:

  • <section> is the parent of the heading and paragraph.
  • <h2> and <p> are children of the section.
  • <strong> is a child of the paragraph.
  • The paragraph and heading are siblings because they share the same parent.
  • The section is an ancestor of the strong element.

Correct Nesting Order

When elements overlap in the source, close them in the reverse order in which they were opened.

Correct:

<p>This is <strong>very important</strong> information.</p>

The strong element opens inside the paragraph and closes before the paragraph closes.

Incorrect:

<p>This is <strong>very important</p></strong>

The paragraph closes before the strong element. This is malformed nesting. Browsers attempt to recover from many markup errors, but the resulting DOM may not match your intention.

Visualizing the Element Tree

<main>
  <section>
    <h2>Courses</h2>
    <p>Learn <strong>HTML</strong> today.</p>
  </section>
</main>

The simplified tree is:

main
└── section
    ├── h2
    └── p
        └── strong

This hierarchy matters because CSS selectors, JavaScript DOM traversal, accessibility APIs, and browser rendering all depend on the document structure.


10. Elements That Cannot Be Nested Arbitrarily

Not every element can contain every other element. HTML defines content models that describe the kinds of content allowed inside an element.

Example 1: Paragraphs and Block-Level Content

A paragraph element accepts phrasing content, not arbitrary sectioning or flow elements. A paragraph is automatically closed by the HTML parser when certain elements that cannot be inside a paragraph begin.

Do not write this when you intend a div inside a paragraph:

<p>
  Text before
  <div>A separate container</div>
  Text after
</p>

The browser may close the paragraph before the div and create a different DOM structure than expected. Use separate elements instead:

<p>Text before the container.</p>

<div>A separate container</div>

<p>Text after the container.</p>

Example 2: Links Inside Links

An anchor element must not contain another anchor element or other interactive descendants that violate its content model.

Incorrect:

<a href="/courses">
  Browse courses
  <a href="/html">HTML course</a>
</a>

Correct:

<p>
  <a href="/courses">Browse all courses</a>
  or
  <a href="/html">view the HTML course</a>.
</p>

Example 3: Lists

List items belong inside list containers such as <ul> or <ol>.

Correct:

<ul>
  <li>HTML</li>
  <li>CSS</li>
  <li>JavaScript</li>
</ul>

A browser may attempt to repair invalid list markup, but relying on automatic correction makes code harder to understand and maintain.

Example 4: Table Structure

Table rows and cells must follow the table content model. Use table row elements inside the appropriate table section or table structure.

<table>
  <thead>
    <tr>
      <th scope="col">Course</th>
      <th scope="col">Level</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>HTML5 Mastery</td>
      <td>Beginner</td>
    </tr>
  </tbody>
</table>

Use the content model for the specific element you are writing. The HTML standard defines which children are permitted, so visual appearance alone is not enough to determine whether nesting is valid.


11. Whitespace, Indentation and Readability

HTML usually collapses consecutive spaces and line breaks in ordinary rendered text into a single space. Indentation is primarily for developers reading the source.

<p>
  Welcome
  to
  Codementrix.
</p>

This will ordinarily render as “Welcome to Codementrix.” The line breaks in the source do not automatically create separate visible lines.

Use indentation to make nested structures easier to read:

<article>
  <h2>HTML Basics</h2>
  <p>Learn elements and attributes.</p>
  <a href="/courses/html">Explore the course</a>
</article>

Consistent indentation helps you spot missing closing tags and incorrect nesting. It does not change the element hierarchy by itself.


12. Attribute Names, Values and Duplicate Attributes

In HTML syntax, attribute names are ASCII case-insensitive, although lowercase names are the normal convention. For example, class and CLASS are interpreted as the same HTML attribute name.

Prefer lowercase:

<p class="notice">Please read this notice.</p>

Attribute values may have different case rules depending on the attribute. For example, a custom class name is case-sensitive when matched by CSS class selectors. Do not assume all attribute values are case-insensitive.

Avoid Duplicate Attributes

Do not write the same attribute more than once on a single element.

Incorrect:

<div class="card" class="featured">Course details</div>

Correct:

<div class="card featured">Course details</div>

When you need multiple class names, separate them with whitespace in one class attribute.

Duplicate attributes make HTML non-conforming and can be handled differently by tools and parsers. Write each attribute only once.


13. HTML Attributes and Security Awareness

HTML attributes can influence navigation, form behavior, media embedding, and JavaScript interactions. When working with user-provided content, never assume a value is safe just because it appears inside an HTML attribute.

Example: Unsafe String Construction

Suppose an application inserts user-provided text directly into an HTML attribute. If the value is not properly handled, an attacker may be able to break out of the intended attribute and inject markup.

For example, concatenating untrusted data into HTML strings can be dangerous:

// Conceptual JavaScript example — avoid this pattern:
const html = '<div title="' + userInput + '">Details</div>';

Safer approaches depend on the application. Prefer creating DOM elements and assigning text through properties such as textContent, and validate or safely handle URLs before placing them into navigation attributes. For server-rendered applications, use the framework's proper HTML escaping mechanisms.

Do not insert untrusted data into event-handler attributes such as onclick. Avoid inline JavaScript event handlers in modern application code and use event listeners where appropriate.

Remember: HTML syntax alone does not sanitize untrusted input. Security depends on how data is validated, escaped, and used in the application.


14. Real-World Example: A Course Card

Let's combine elements, attributes, and nesting rules in a simple course card suitable for a learning website.

<article class="course-card" id="html-course">
  <img
    src="html5-course.jpg"
    alt="HTML5 course illustration"
    width="320"
    height="180"
  >

  <div class="course-card__content">
    <p class="course-card__level">Beginner</p>

    <h2>HTML5 Mastery</h2>

    <p>
      Learn HTML elements, attributes, nesting,
      semantic markup and accessible page structure.
    </p>

    <a href="/courses/html5-mastery">
      View course
    </a>
  </div>
</article>

What this example demonstrates:

  • <article> groups a self-contained course card.
  • class attributes allow styling and reusable component patterns.
  • id identifies the specific card in the document.
  • src, alt, width, and height configure the image.
  • The div groups the card's content.
  • The heading identifies the course title.
  • The anchor provides navigation to the course page.
  • Every non-void element is properly nested and closed.

The image filename is an example. Replace it with a real image path when using this markup in your own project.


15. Common Mistakes and How to Fix Them

Mistake 1: Forgetting a Closing Tag

<strong>Important information

Fix:

<strong>Important information</strong>

Some omitted end tags are allowed by the standard, but do not rely on omission unless you understand the specific rule.

Mistake 2: Closing Tags in the Wrong Order

<div><p>Hello</div></p>

Fix:

<div><p>Hello</p></div>

Mistake 3: Forgetting Quotes Around Attribute Values

<input placeholder=Enter your name>

Fix:

<input placeholder="Enter your name">

Mistake 4: Using a Closing Tag for a Void Element

<img src="logo.png" alt="Logo"></img>

Fix:

<img src="logo.png" alt="Logo">

Mistake 5: Duplicating an Attribute

<p id="first" id="second">Hello</p>

Fix by choosing one identifier:

<p id="first">Hello</p>

Mistake 6: Reusing an ID

<p id="notice">First notice</p>
<p id="notice">Second notice</p>

Fix by using different IDs or a reusable class:

<p class="notice">First notice</p>
<p class="notice">Second notice</p>

Mistake 7: Putting a Block Container Inside a Paragraph

<p>
  Intro text
  <div>Container</div>
</p>

Fix by separating the paragraph and container into their own elements.

Mistake 8: Assuming a Slash Makes Any Element Self-Closing

<div />

In HTML, the slash does not close a non-void element in the XML sense. Use an explicit closing tag:

<div>Content</div>

16. Practical Exercises

Complete these exercises before attempting the quiz. Use a modern browser and a code editor.

Exercise 1: Identify the Parts

Examine this element:

<a href="/about" class="nav-link">About Us</a>

Identify the opening tag, closing tag, element name, attributes, attribute values, and content.

Exercise 2: Correct the Markup

Fix the errors in the following code:

<div class="card" class="featured">
  <p>Learn <strong>HTML</p></strong>
  <img src="course.jpg"></img>
</div>

Check for duplicate attributes, incorrect nesting, and invalid use of a void element.

Exercise 3: Build a Profile Card

Create an HTML profile card that includes:

  • An outer <article> with a class attribute.
  • An image with a meaningful alt attribute.
  • A heading for the person's name.
  • A paragraph describing their role.
  • A link to a portfolio page.

Exercise 4: Experiment with Attributes

Create a form input that has a unique ID, a name, an email type, a placeholder, and the required attribute.

<input
  type="email"
  id="contact-email"
  name="email"
  placeholder="Enter your email"
  required
>

Try removing required and observe how the browser's built-in validation behavior changes when the form is submitted. Remember that client-side validation is not a replacement for server-side validation.

Exercise 5: Inspect the DOM

  1. Save a small HTML page in your editor.
  2. Open the page in a browser.
  3. Open Developer Tools using the browser's Inspect option.
  4. Find the Elements or Inspector panel.
  5. Expand the elements and identify parent, child, and sibling relationships.
  6. Compare the DOM tree with the HTML source you wrote.

Browsers may repair malformed markup while parsing it, so the DOM tree can differ from the source text.


17. Lesson Summary

  • An HTML element is the complete construct; tags are the markup delimiters used to represent it.
  • Most elements have opening and closing tags, while void elements do not have closing tags.
  • Attributes configure elements and are normally written in the opening tag.
  • Quoting attribute values consistently improves readability and prevents parsing mistakes.
  • Boolean attributes are true when present; writing a value such as "false" does not turn them off.
  • Proper nesting follows the permitted content model for each element.
  • IDs should be unique in a document; class names can be reused.
  • HTML parsers may recover from malformed markup, but browser recovery does not make the source conforming.
  • Use browser Developer Tools and an HTML validator to detect structural problems.

18. Quiz: HTML Elements, Tags, Attributes and Nesting Rules

Test your understanding with these 10 questions. Each question includes four options, the correct answer, and an explanation for every option. Expand the answer details after choosing your answer.

Scoring suggestion: Award 1 point for each correct answer. A score of 8/10 or higher indicates a good understanding of this lesson. This HTML quiz reveals answers but does not automatically score or save progress unless your course platform adds JavaScript or quiz functionality.

Question 1: What is an HTML element?

  1. Only the opening tag
  2. The complete HTML construct, including its tags and content where applicable
  3. Only an attribute value
  4. A CSS selector
Show correct answer and explanations

Correct answer: B

  • A — Incorrect: An opening tag is only one part of many HTML elements.
  • B — Correct: An element includes the relevant tags and its content, where applicable.
  • C — Incorrect: An attribute value is just the value assigned to an attribute.
  • D — Incorrect: A CSS selector targets elements for styling; it is not an HTML element.

Question 2: Which is a void element in HTML?

  1. <div>
  2. <section>
  3. <img>
  4. <strong>
Show correct answer and explanations

Correct answer: C

  • A — Incorrect: A div is a non-void element and normally has an end tag.
  • B — Incorrect: A section is a non-void element.
  • C — Correct: An img element is void and cannot contain child nodes.
  • D — Incorrect: A strong element contains content and has an end tag.

Question 3: What does the href attribute usually specify on an anchor element?

  1. The destination URL of the link
  2. The font size of the link
  3. The link's HTML closing tag
  4. The browser's screen resolution
Show correct answer and explanations

Correct answer: A

  • A — Correct: The href attribute specifies the hyperlink destination.
  • B — Incorrect: Font size is generally controlled by CSS.
  • C — Incorrect: The closing tag is written as </a>.
  • D — Incorrect: href does not configure screen resolution.

Question 4: Which attribute is a Boolean attribute?

  1. placeholder
  2. href
  3. required
  4. alt
Show correct answer and explanations

Correct answer: C

  • A — Incorrect: placeholder takes text that describes the expected input.
  • B — Incorrect: href takes a URL or other valid link reference.
  • C — Correct: required is true when present on a supported form control.
  • D — Incorrect: alt provides a text alternative for an image; it is not Boolean.

Question 5: What happens if you write required="false" on a supported input?

  1. The input becomes optional
  2. The browser treats the attribute as absent
  3. The attribute is present, so it is considered true
  4. The browser automatically deletes the input
Show correct answer and explanations

Correct answer: C

  • A — Incorrect: The word "false" does not disable a Boolean attribute.
  • B — Incorrect: The attribute is still present in the markup.
  • C — Correct: Boolean attributes are true when present. Remove required to make the control not required.
  • D — Incorrect: required does not delete an element.

Question 6: Which example shows correct nesting?

  1. <p><strong>Hello</p></strong>
  2. <p><strong>Hello</strong></p>
  3. <p><strong>Hello</p>
  4. </strong>Hello<p>
Show correct answer and explanations

Correct answer: B

  • A — Incorrect: The paragraph closes before the nested strong element.
  • B — Correct: The inner strong element closes before the outer paragraph.
  • C — Incorrect: The strong element has no explicit closing tag in this example, and the nesting is incomplete.
  • D — Incorrect: The closing strong tag appears before its corresponding opening tag.

Question 7: Which statement about id and class is correct?

  1. An ID should be unique within the document, while classes can be reused
  2. Every element must have an ID
  3. A class can only be assigned to one element
  4. An ID is used only for image files
Show correct answer and explanations

Correct answer: A

  • A — Correct: IDs identify individual elements, while classes support reusable grouping and styling.
  • B — Incorrect: Most HTML elements do not require an ID.
  • C — Incorrect: The same class can be used on many elements.
  • D — Incorrect: IDs can identify many kinds of elements, not only images.

Question 8: What is the problem with this markup?

<div class="card" class="featured">Course</div>
  1. HTML elements cannot have classes
  2. The div element is a void element
  3. The same attribute is repeated twice
  4. Text cannot appear inside a div
Show correct answer and explanations

Correct answer: C

  • A — Incorrect: A div can have a class attribute.
  • B — Incorrect: A div is not a void element.
  • C — Correct: The class attribute is duplicated. Use class="card featured" instead.
  • D — Incorrect: A div can contain text and other permitted content.

Question 9: Why should you quote attribute values consistently?

  1. HTML requires every attribute value to be a number
  2. Quotes make values containing spaces safe to parse and improve readability
  3. Quotes automatically validate all URLs
  4. Quotes turn every attribute into a Boolean attribute
Show correct answer and explanations

Correct answer: B

  • A — Incorrect: Attribute values can be text, URLs, numbers, and other permitted values.
  • B — Correct: Quoting avoids ambiguity for values with spaces and makes markup more readable.
  • C — Incorrect: Quotes do not validate whether a URL is safe or correct.
  • D — Incorrect: Quoting a value does not change the attribute's type.

Question 10: What is the best way to check whether your HTML markup conforms to HTML rules?

  1. Check only whether the page looks correct
  2. Use an HTML validator and inspect the DOM in browser Developer Tools
  3. Remove every closing tag
  4. Put every element inside a paragraph
Show correct answer and explanations

Correct answer: B

  • A — Incorrect: Browsers can recover from invalid markup, so visual appearance alone does not prove conformance.
  • B — Correct: An HTML validator can report conformance problems, and Developer Tools help you inspect the parsed DOM.
  • C — Incorrect: Many elements require closing tags, and removing them indiscriminately creates errors.
  • D — Incorrect: Paragraphs have content restrictions and cannot contain arbitrary elements.

19. Recommended Practice Before Moving On

Before starting Section 4, make sure you can:

  • Recognize an element, its tags, and its attributes.
  • Identify void elements and avoid adding closing tags to them.
  • Write attributes with quoted values.
  • Explain how Boolean attributes work.
  • Correct mismatched tags and invalid nesting.
  • Use IDs and classes appropriately.
  • Inspect the DOM and validate your markup.

Next section: Section 4 — Headings, Paragraphs, Text Formatting and Quotations.

End of Section 3 — Codementrix HTML5 Mastery.