Back to JavaScript Fundamentals

HTML Conditional Statements: A Complete Guide

Learn how to add conditional statements to HTML using data attributes, JavaScript, and modern web techniques. Perfect for creating dynamic, interactive web pages.
8 min readLogan FordLogan Ford

Introduction

HTML conditional statements allow you to create dynamic, interactive web pages that respond to user actions and different conditions. While HTML itself doesn't have built-in conditional logic, we can implement it through various techniques. This guide will show you how to add conditional statements to your HTML effectively.

Understanding HTML Conditional Statements

Conditional statements in HTML are implemented through a combination of:

  • HTML data attributes
  • JavaScript integration
  • CSS classes and selectors
  • Modern web APIs

Let's explore each approach and when to use them.

Using Data Attributes

Data attributes provide a powerful way to add conditional logic directly in HTML elements. Let's explore how they work and their various use cases in detail.

Basic Data Attributes

Data attributes allow you to store custom data directly in HTML elements. They always start with data- followed by your custom name:


1<!-- Basic visibility control -->
2<div data-visible="true">
3This content is visible
4</div>
5
6<!-- Role-based content display -->
7<div data-role="admin">
8Admin-only content
9</div>
10
11<!-- State management for UI elements -->
12<button data-state="loading">
13Processing...
14</button>
15
16<!-- Multiple conditions on a single element -->
17<div data-visible="true" data-feature="premium" data-theme="dark">
18Premium dark theme content
19</div>

JavaScript Control

Here's how to manipulate elements based on their data attributes using JavaScript:

1// Basic visibility toggle
2// This code finds an element with data-visible="true" and shows/hides it based on login status
3const element = document.querySelector('[data-visible="true"]');
4if (userIsLoggedIn) {
5 element.style.display = 'block'; // Show the element
6} else {
7 element.style.display = 'none'; // Hide the element
8}
9
10// Role-based access control
11// This code manages multiple admin elements based on user permissions
12const adminElements = document.querySelectorAll('[data-role="admin"]');
13adminElements.forEach(element => {
14 if (userHasAdminRole) {
15 element.classList.remove('hidden'); // Show admin content
16 } else {
17 element.classList.add('hidden'); // Hide admin content
18 }
19});
20
21// State management for UI elements
22// This demonstrates how to handle different states of a button
23const button = document.querySelector('button[data-state]');
24function updateButtonState(state) {
25 button.dataset.state = state; // Update the data-state attribute
26
27 // Handle different states with appropriate UI changes
28 switch(state) {
29 case 'loading':
30 button.textContent = 'Processing...';
31 button.disabled = true;
32 break;
33 case 'error':
34 button.textContent = 'Try Again';
35 button.disabled = false;
36 break;
37 case 'success':
38 button.textContent = 'Completed!';
39 button.disabled = true;
40 break;
41 default:
42 button.textContent = 'Submit';
43 button.disabled = false;
44 }
45}

CSS Integration

Data attributes can be targeted directly in CSS for conditional styling:

1/* Hide elements marked as not visible */
2[data-visible="false"] {
3 display: none;
4}
5
6/* Style elements based on their state */
7[data-state="loading"] {
8 opacity: 0.7; /* Dim the element */
9 cursor: wait; /* Show loading cursor */
10}
11
12[data-state="error"] {
13 border-color: red; /* Red border for error state */
14 color: red; /* Red text for error state */
15}
16
17/* Apply theme-based styling */
18[data-theme="dark"] {
19 background-color: #333;
20 color: white;
21}
22
23/* Complex selectors combining multiple conditions */
24[data-visible="true"][data-feature="premium"] {
25 border: 2px solid gold; /* Special border for premium content */
26}

Implementation Best Practices

When using data attributes for conditional logic, follow these guidelines:

  1. Naming Conventions

    • Use clear, descriptive names (e.g., data-state instead of data-s)
    • Use kebab-case for multi-word attributes (e.g., data-user-role)
    • Keep names consistent across your application
  2. Value Formats

    • Use boolean strings when possible ("true"/"false")
    • Keep values simple and lowercase
    • Use consistent value formats across similar attributes
  3. Performance Considerations

    • Cache DOM selections for frequently accessed elements
    • Use event delegation for dynamic elements
    • Minimize DOM updates when changing states
  4. Maintainability

    • Document your data attributes in your project's documentation
    • Create a central registry of data attributes used in your application
    • Consider using TypeScript for better type checking of data attributes
  5. Security

    • Never store sensitive data in data attributes
    • Validate data attribute values before using them
    • Sanitize any user-provided values

Remember that data attributes are always stored as strings in the DOM. When comparing values in JavaScript, you'll need to handle type conversion appropriately:

1const element = document.querySelector('[data-count="5"]');
2const count = element.dataset.count; // Returns "5" as a string
3
4// Correct way to compare numbers
5if (parseInt(count) === 5) {
6 console.log('Count is 5');
7}
8
9// Correct way to compare booleans
10const isVisible = element.dataset.visible === 'true'; // Converts to boolean

JavaScript Integration

JavaScript provides powerful ways to implement conditional logic:

1<div id="userContent">
2 <!-- Content will be conditionally rendered here -->
3</div>
4
5<script>
6 const userContent = document.getElementById('userContent');
7
8 if (userIsAuthenticated) {
9 userContent.innerHTML = `
10 <h2>Welcome back, ${username}!</h2>
11 <button onclick="logout()">Logout</button>
12 `;
13 } else {
14 userContent.innerHTML = `
15 <h2>Please log in</h2>
16 <button onclick="login()">Login</button>
17 `;
18 }
19</script>

Common Use Cases

Here are practical examples of HTML conditional statements:

1. Toggle Navigation Menu

1<nav data-expanded="false">
2 <button onclick="toggleMenu()">Menu</button>
3 <ul class="menu-items">
4 <li>Home</li>
5 <li>About</li>
6 <li>Contact</li>
7 </ul>
8</nav>
9
10<script>
11 function toggleMenu() {
12 const nav = document.querySelector('nav');
13 const isExpanded = nav.dataset.expanded === 'true';
14 nav.dataset.expanded = !isExpanded;
15 }
16</script>

2. Form Validation

1<form id="signupForm">
2 <input
3 type="email"
4 data-valid="false"
5 onchange="validateEmail(this)"
6 >
7 <span data-error="email" hidden>
8 Please enter a valid email
9 </span>
10</form>
11
12<script>
13 function validateEmail(input) {
14 const isValid = input.value.includes('@');
15 input.dataset.valid = isValid;
16 const error = document.querySelector('[data-error="email"]');
17 error.hidden = isValid;
18 }
19</script>

Best Practices

Follow these guidelines for clean, maintainable code:

  1. Use Semantic Data Attributes
1<!-- Good -->
2<div data-theme="dark">
3<!-- Avoid -->
4<div data-x="1">
  1. Keep Logic Separate
1<!-- HTML -->
2<button data-action="save">Save</button>
3
4<!-- JavaScript -->
5<script>
6 document.querySelector('[data-action="save"]')
7 .addEventListener('click', handleSave);
8</script>
  1. Progressive Enhancement
1<div class="card">
2 <h2>Content</h2>
3 <noscript>
4 JavaScript is required for full functionality
5 </noscript>
6</div>

Dynamic Templates

The following example demonstrates how to create dynamic HTML templates with conditional rendering:


1<template id="userTemplate">
2 <div class="user-card">
3 <img src="{{avatar}}" alt="{{name}}">
4 <h3>{{name}}</h3>
5 {{#if isAdmin}}
6 <span class="badge">Admin</span>
7 {{/if}}
8 </div>
9</template>
10
11<script>
12 // Get reference to the template element
13 const template = document.getElementById('userTemplate');
14
15 // Sample user data object with properties that will be inserted
16 const user = {
17 name: 'John Doe', // Will replace {{name}}
18 avatar: '/avatar.jpg', // Will replace {{avatar}}
19 isAdmin: true // Controls if admin badge shows
20 };
21
22 // The renderTemplate function would:
23 // 1. Take the template HTML and user data
24 // 2. Replace {{variables}} with actual values
25 // 3. Process {{#if}} conditions based on data
26 // 4. Return the final HTML with real values
27 renderTemplate(template, user);
28</script>

Let's break down what's happening:

  1. The <template> tag holds our HTML structure with placeholders like {{name}} and conditional blocks using {{#if}} syntax

  2. Inside the template:

    • {{name}} and {{avatar}} are placeholders that will be replaced with real data
    • The {{#if isAdmin}} block only renders when user.isAdmin is true
  3. The JavaScript:

    • Stores the template reference and user data
    • The renderTemplate function (not shown) would process the template string
    • Replaces variables and evaluates conditions based on the user object
    • Outputs final HTML with all placeholders replaced

This pattern allows you to maintain reusable HTML templates that can render differently based on data conditions.

Practice Examples

Try these exercises to improve your skills:

  1. Create a theme switcher using data attributes
  2. Build a conditional navigation menu
  3. Implement form validation with visual feedback

Here are some practice questions to test your understanding:



Ready to master HTML and web development? Join TechBlitz for daily coding challenges, personalized learning paths, and a supportive community of developers. Start your journey today at TechBlitz.

Learn to code, faster

Join 810+ developers who are accelerating their coding skills with TechBlitz.

Share this article