JavaScript Fundamentals with AI
Add interactivity to your websites with AI — DOM manipulation, event handling, form validation, and dynamic content updates using vanilla JavaScript.
Premium Course Content
This lesson is part of a premium course. Upgrade to Pro to unlock all premium courses and content.
- Access all premium courses
- 1000+ AI skill templates included
- New content added weekly
🔄 Quick Recall: In the last lesson, you styled your pages with CSS — responsive layouts, design tokens, and dark mode. Now let’s make things interactive with JavaScript.
DOM Manipulation
The DOM (Document Object Model) is how JavaScript interacts with your HTML. Here’s how to work with AI for common DOM tasks:
Selecting and Modifying Elements
Write vanilla JavaScript to:
1. Select the element with id="hero-title" and change its text
2. Select all elements with class="card" and add a "featured" class to the first one
3. Create a new paragraph element, set its text content, and append it to the element with id="content"
Requirements:
- Use document.querySelector and document.querySelectorAll (not getElementById)
- Use textContent for safe text updates
- No external libraries
- Add comments explaining each step
Dynamic Content Creation
Write vanilla JavaScript to dynamically create a list of items from an array:
Data:
const items = [
{ title: "Item 1", description: "Description 1", category: "A" },
{ title: "Item 2", description: "Description 2", category: "B" },
// ... more items
];
Requirements:
- Create an unordered list element
- For each item, create an li containing the title in a strong tag and description in a paragraph
- Append the complete list to the element with id="item-list"
- Use document.createElement and textContent for safe DOM updates
- Use a document fragment for performance (batch DOM insertions)
Vanilla JavaScript only, no dependencies.
✅ Quick Check: Why use a document fragment for creating multiple elements?
Every time you append an element to the page, the browser recalculates layout. Adding 50 items one-by-one means 50 recalculations. A document fragment is an invisible container — you build everything inside it, then append once. One recalculation instead of 50. AI sometimes generates the one-by-one approach because it’s simpler to write, but the performance difference matters with larger lists.
Event Handling
Click Events and Delegation
Write vanilla JavaScript for an interactive FAQ accordion:
HTML structure:
- Multiple FAQ items, each with a question (button) and answer (div)
- Clicking a question toggles its answer visibility
- Only one answer open at a time (accordion behavior)
Requirements:
- Use event delegation (single listener on the parent container, not one per button)
- Toggle aria-expanded on the button
- Toggle a "hidden" class on the answer div
- Add smooth height transition with CSS class toggling
- Keyboard accessible (Enter and Space trigger toggle)
Vanilla JavaScript, no dependencies. Include the HTML structure in the output.
Form Validation
Write client-side form validation in vanilla JavaScript:
Form fields:
- Name (required, minimum 2 characters)
- Email (required, valid email format)
- Phone (optional, but if filled must match a phone pattern)
- Message (required, minimum 10 characters, maximum 500)
Validation behavior:
- Validate on form submit
- Show error messages below each invalid field using textContent (never inject raw HTML)
- Use aria-invalid and aria-describedby for accessibility
- Prevent form submission if any field is invalid
- Clear error messages when user starts correcting a field (input event)
- Show success message when form is valid
Vanilla JavaScript, no dependencies.
Working with Local Storage
Write vanilla JavaScript for a simple favorites/bookmarks feature:
Behavior:
- Each card has a heart/star button
- Clicking the button toggles the item as a favorite
- Favorites are saved to localStorage
- On page load, previously favorited items are restored
- A "View Favorites" filter shows only favorited items
Requirements:
- Store an array of item IDs in localStorage (JSON.stringify/parse)
- Handle the case where localStorage is unavailable (try-catch)
- Update button visual state (filled/outline) based on favorite status
- Include aria-pressed attribute on toggle buttons
Vanilla JavaScript, no dependencies.
✅ Quick Check: Why check if localStorage is unavailable?
Because localStorage isn’t guaranteed. Private/incognito browsing modes may block it. Some browsers disable it when storage is full. Corporate firewalls can restrict it. If your code assumes localStorage.setItem() always works, one blocked call crashes everything. A try-catch around localStorage operations ensures your page still functions — it just won’t remember favorites between sessions.
Security Review for AI-Generated JavaScript
Always check AI output for these common vulnerabilities:
Review this JavaScript for security issues:
[paste your JavaScript]
Check for:
1. Unsanitized user data inserted into the DOM (XSS risk)
2. Dynamic code execution patterns (code injection risk)
3. Unvalidated URL parameters used in page logic
4. Sensitive data stored in localStorage without encryption
5. Missing input sanitization on form data
6. Event handlers that could be triggered maliciously
7. API keys or secrets hardcoded in client-side code
For each issue found, explain the risk and provide a secure alternative.
Exercise: Add Interactivity to Your Page
- Add a FAQ accordion to your page using event delegation
- Create a form with client-side validation (at least 4 fields)
- Implement a favorites feature with localStorage persistence
- Run the security review prompt on all your JavaScript
- Test keyboard navigation — can you use every feature without a mouse?
Key Takeaways
- Always specify “vanilla JavaScript, no dependencies” in prompts to get universally compatible code
- Use
textContentfor safe text updates and sanitize any HTML content before inserting it into the DOM - Event delegation (one listener on the parent) is more efficient and maintainable than individual listeners on each element
- Document fragments batch DOM insertions for better performance with dynamic content
- Wrap localStorage, API calls, and JSON parsing in try-catch blocks — never assume external operations succeed
- Always run a security review on AI-generated JavaScript, checking for unsanitized user data and hardcoded secrets
Up Next: In the next lesson, you’ll build interactive features and connect to external APIs — fetching data, handling responses, and creating dynamic web applications.
Knowledge Check
Complete the quiz above first
Lesson completed!