HTML with JavaScript
HTML with JavaScript
HTML provides the structure of a webpage, CSS controls its presentation, and JavaScript adds behaviour and interactivity.
HTML → Structure & Meaning
CSS → Presentation & Layout
JavaScript → Behaviour & Interactivity
JavaScript can respond to user actions, modify HTML content, change styles, validate forms, communicate with web services, store information in the browser and create dynamic applications.
1. What Can JavaScript Do?
JavaScript enables webpages to respond dynamically to users and to application state.
- Change HTML content.
- Change HTML attributes.
- Change CSS styles.
- Show or hide elements.
- Respond to clicks and keyboard input.
- Validate form data.
- Create interactive menus and components.
- Communicate with web APIs.
- Store data in the browser.
- Update a page without a full page reload.
2. Adding JavaScript to HTML
JavaScript can be included in HTML in several ways. The most common approaches are inline scripts, internal scripts and external JavaScript files.
3. Inline JavaScript
JavaScript can be written directly inside an HTML event attribute.
<button onclick="alert('Hello!')">
Click Me
</button>
Avoid putting application logic directly into HTML event attributes. Separating HTML and JavaScript makes code easier to maintain and reuse.
4. Internal JavaScript
JavaScript can be placed inside a <script> element within an HTML document.
<script>
function greet() {
alert("Welcome to Web Development!");
}
</script>
The function can then be connected to an appropriate user interaction.
5. External JavaScript
In larger projects, JavaScript is generally placed in a separate .js file.
HTML
<script src="js/script.js"></script>
script.js
function greet() {
alert("Welcome!");
}
Use external JavaScript files for maintainable, reusable and scalable websites.
6. Where Should the <script> Element Be Placed?
JavaScript can be loaded in the document head or body. For modern websites, external scripts are commonly loaded using defer in the head.
<head>
<script
src="js/script.js"
defer>
</script>
</head>
The defer attribute tells the browser to download the script while parsing the document and execute it after the document has been parsed.
| Approach | Typical Use |
|---|---|
| Inline event attribute | Simple demonstrations; generally avoid in production. |
| Internal script | Small single-page examples. |
| External script | Reusable application code. |
defer |
External scripts that should execute after HTML parsing. |
7. Basic JavaScript Syntax
let studentName = "Alex";
console.log(studentName);
JavaScript statements commonly perform operations such as declaring variables, calling functions and modifying objects.
8. Variables
Variables store values that a program may use or manipulate. Modern JavaScript primarily uses let and const.
let score = 85;
const schoolName = "Green Valley Academy";
score = 90;
| Keyword | Purpose |
|---|---|
let |
Declares a block-scoped variable that can be reassigned. |
const |
Declares a block-scoped binding that cannot be reassigned. |
var |
Older variable declaration mechanism with function scope. |
Prefer const by default and use let when reassignment is required.
9. Common JavaScript Data Types
| Type | Example |
|---|---|
| String | "HTML" |
| Number | 95 |
| Boolean | true |
| Undefined | undefined |
| Null | null |
| Object | { name: "Alex" } |
| Array | ["HTML", "CSS", "JS"] |
10. JavaScript Functions
A function is a reusable block of code designed to perform a particular task.
function calculateTotal(price, quantity) {
return price * quantity;
}
const total = calculateTotal(500, 2);
console.log(total);
Functions can accept parameters and can return values using the return statement.
11. JavaScript Events
An event represents an occurrence that JavaScript can respond to, such as a click, keyboard action, form submission or change in an input.
| Event | Example Situation |
|---|---|
click |
User clicks a button. |
input |
User changes the value of an input. |
change |
An input's committed value changes. |
submit |
A form is submitted. |
keydown |
A keyboard key is pressed. |
DOMContentLoaded |
The initial HTML document has been parsed. |
12. addEventListener()
The addEventListener() method is a standard way to register an event handler.
const button = document.querySelector("#showMessage");
button.addEventListener("click", function () {
alert("Hello from JavaScript!");
});
Prefer addEventListener() over inline event attributes because it keeps behaviour separate from HTML markup.
13. The DOM
The Document Object Model (DOM) represents an HTML document as a structured tree of objects that JavaScript can access and manipulate.
document
↓
html
↓
body
↓
h1
↓
Text
Through the DOM, JavaScript can find elements, change their content, modify attributes, add or remove elements and respond to events.
14. Selecting HTML Elements
getElementById()
const heading =
document.getElementById("pageTitle");
querySelector()
const heading =
document.querySelector("#pageTitle");
querySelectorAll()
const items =
document.querySelectorAll(".course");
| Method | Purpose |
|---|---|
getElementById() |
Finds an element by its ID. |
querySelector() |
Returns the first element matching a CSS selector. |
querySelectorAll() |
Returns all elements matching a CSS selector. |
15. Changing HTML Content
JavaScript can update the content of an element.
<h1 id="title">
Original Heading
</h1>
<script>
const title =
document.querySelector("#title");
title.textContent = "Updated Heading";
</script>
Use textContent when inserting plain text. Be cautious with innerHTML when content may contain untrusted input.
16. innerHTML
The innerHTML property can read or replace the HTML markup inside an element.
const message =
document.querySelector("#message");
message.innerHTML =
"<strong>Welcome!</strong>";
Never insert untrusted user input into innerHTML without appropriate sanitization. Unsafe use can create cross-site scripting (XSS) vulnerabilities.
17. Changing HTML Attributes
const image =
document.querySelector("#courseImage");
image.setAttribute(
"alt",
"HTML course illustration"
);
JavaScript can also read attributes using getAttribute() and remove them using removeAttribute().
18. Changing CSS with JavaScript
JavaScript can modify an element's inline style.
const message =
document.querySelector("#message");
message.style.fontWeight = "bold";
For maintainable applications, prefer adding or removing CSS classes instead of creating large collections of inline styles from JavaScript.
19. classList
The classList API provides convenient methods for manipulating CSS classes.
const card =
document.querySelector(".card");
card.classList.add("featured");
card.classList.remove("hidden");
card.classList.toggle("active");
| Method | Purpose |
|---|---|
add() |
Adds a class. |
remove() |
Removes a class. |
toggle() |
Adds the class if absent and removes it if present. |
contains() |
Checks whether a class exists. |
20. JavaScript and HTML Forms
JavaScript can respond to form submission, read input values, validate information and provide immediate feedback.
<form id="registrationForm">
<label for="name">
Name
</label>
<input
id="name"
name="name"
required>
<button type="submit">
Register
</button>
</form>
const form =
document.querySelector("#registrationForm");
form.addEventListener("submit", function (event) {
event.preventDefault();
const name =
document.querySelector("#name").value.trim();
console.log(name);
});
21. The Event Object
Event handlers receive an event object containing information about the event.
button.addEventListener("click", function (event) {
console.log(event.type);
});
For form submission, event.preventDefault() can prevent the browser's default submission behaviour when appropriate.
22. Form Validation
HTML provides built-in validation features, while JavaScript can implement additional client-side validation and user feedback.
<input
type="email"
id="email"
required>
JavaScript can inspect validity using the checkValidity() method.
const email =
document.querySelector("#email");
if (!email.checkValidity()) {
console.log("Please enter a valid email.");
}
Client-side validation improves user experience but must not be treated as the only security control. Important validation must also be performed on the server.
23. Creating HTML Elements Dynamically
JavaScript can create new DOM elements and insert them into the document.
const paragraph =
document.createElement("p");
paragraph.textContent =
"This paragraph was created using JavaScript.";
document.body.appendChild(paragraph);
24. Removing HTML Elements
const notification =
document.querySelector(".notification");
notification.remove();
This removes the selected element from the document.
25. Arrays and Dynamic HTML
Arrays can store collections of values and can be used to generate dynamic content.
const courses = [
"HTML",
"CSS",
"JavaScript"
];
courses.forEach(function (course) {
console.log(course);
});
26. JavaScript Objects
Objects store related data as properties and can also contain methods.
const student = {
name: "Alex",
course: "Web Development",
score: 92
};
console.log(student.name);
27. Conditional Statements
Conditional statements allow a program to make decisions.
const score = 82;
if (score >= 90) {
console.log("Excellent");
} else if (score >= 60) {
console.log("Good");
} else {
console.log("Needs improvement");
}
28. Loops
Loops repeat operations over a sequence or while a condition remains true.
const courses = [
"HTML",
"CSS",
"JavaScript"
];
for (const course of courses) {
console.log(course);
}
29. JavaScript and Web APIs
JavaScript can communicate with web services using browser APIs such as the Fetch API.
fetch("/api/courses")
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
Modern applications commonly use APIs to retrieve or submit data without requiring every interaction to load a completely new HTML document.
30. async and await
The async and await syntax provides a readable way to work with Promises.
async function loadCourses() {
try {
const response =
await fetch("/api/courses");
const courses =
await response.json();
console.log(courses);
} catch (error) {
console.error(error);
}
}
31. Browser Storage
JavaScript can use browser storage mechanisms for certain client-side data.
localStorage
localStorage.setItem(
"theme",
"dark"
);
const theme =
localStorage.getItem("theme");
localStorage persists data across browser sessions until it is removed or cleared.
Do not store passwords, authentication secrets or other highly sensitive information in localStorage.
32. sessionStorage
sessionStorage provides storage associated with a browser tab or session.
sessionStorage.setItem(
"currentCourse",
"HTML"
);
const course =
sessionStorage.getItem("currentCourse");
33. DOMContentLoaded
The DOMContentLoaded event fires when the initial HTML document has been completely parsed.
document.addEventListener(
"DOMContentLoaded",
function () {
console.log("Page is ready.");
}
);
This can be useful when JavaScript needs to access elements that are created by the HTML parser.
34. JavaScript + CSS Classes
A strong pattern is to let JavaScript control application state and let CSS control presentation.
const menuButton =
document.querySelector("#menuButton");
const menu =
document.querySelector("#menu");
menuButton.addEventListener("click", function () {
menu.classList.toggle("is-open");
});
CSS can then define what .is-open looks like.
JavaScript should generally describe what state the interface is in, while CSS determines how that state looks.
35. HTML vs CSS vs JavaScript
| Technology | Primary Role | Example |
|---|---|---|
| HTML | Structure and semantics | Heading, form, table, image |
| CSS | Presentation and layout | Colour, spacing, Grid, Flexbox |
| JavaScript | Behaviour and logic | Click handling, validation, API calls |
36. Complete Example — Interactive Course Card
HTML
<article class="course-card">
<h2>HTML Fundamentals</h2>
<p id="courseStatus">
Course status: Not started
</p>
<button id="startCourse">
Start Course
</button>
</article>
CSS
.course-card {
padding: 24px;
border: 1px solid #ddd;
border-radius: 8px;
}
.course-card.is-started {
border-width: 2px;
}
JavaScript
const button =
document.querySelector("#startCourse");
const card =
document.querySelector(".course-card");
const status =
document.querySelector("#courseStatus");
button.addEventListener("click", function () {
card.classList.add("is-started");
status.textContent =
"Course status: Started";
});
- HTML creates the course card.
- CSS controls its appearance.
- JavaScript listens for the button click.
- JavaScript changes the CSS class.
- JavaScript updates the status text.
37. Debugging JavaScript
Modern browsers provide developer tools for inspecting HTML, CSS and JavaScript.
console.log()
const score = 95;
console.log(score);
console.error()
console.error(
"Unable to load course data."
);
console.table()
const courses = [
"HTML",
"CSS",
"JavaScript"
];
console.table(courses);
Use browser DevTools to inspect the DOM, monitor network requests, view console errors, debug JavaScript and investigate layout problems.
38. Common JavaScript Errors in HTML
| Problem | Possible Cause |
|---|---|
| JavaScript file not loading | Incorrect src path. |
| Element is null | Wrong selector or code runs before the element exists. |
| Click does nothing | Event listener not attached correctly. |
| Unexpected token | JavaScript syntax error. |
| Data does not appear | Incorrect DOM manipulation or asynchronous code issue. |
| API request fails | Incorrect URL, server problem, network issue or CORS restriction. |
39. Security Considerations
JavaScript running in a browser must be developed with security in mind.
- Avoid inserting untrusted content using innerHTML.
- Validate and sanitize data appropriately.
- Never trust client-side validation alone.
- Do not expose secret API keys in browser-side JavaScript.
- Use HTTPS for production websites.
- Apply appropriate authentication and authorization on the server.
Code delivered to a browser is visible to the client. Therefore, passwords, private keys and server-side secrets must not be embedded in frontend JavaScript.
40. HTML + JavaScript Best Practices
- Prefer external JavaScript files for application code.
- Use semantic HTML for document structure.
- Use CSS classes for presentation.
- Use addEventListener() for event handling.
- Prefer const and use let when reassignment is required.
- Keep functions focused on specific responsibilities.
- Use meaningful variable and function names.
- Avoid unnecessary global variables.
- Handle API and asynchronous errors.
- Protect against XSS and other client-side security risks.
- Test keyboard interaction and accessibility.
- Use browser developer tools for debugging.
41. Interview Questions
1. What is JavaScript?
View Answer
JavaScript is a programming language widely used to add behaviour and interactivity to webpages and to build web applications.
2. What is the difference between HTML, CSS and JavaScript?
View Answer
HTML provides structure and semantics, CSS controls presentation and layout, and JavaScript provides behaviour, logic and interactivity.
3. What is the DOM?
View Answer
The Document Object Model is a programmatic representation of an HTML document that JavaScript can access and manipulate.
4. What is an event listener?
View Answer
An event listener registers a function to run when a specified event occurs on an element or other event target.
5. What is the difference between textContent and innerHTML?
View Answer
textContent treats assigned content as text, whereas innerHTML parses assigned content as HTML markup. Untrusted data should not be inserted into innerHTML without appropriate sanitization.
6. Why is addEventListener() preferred over inline onclick attributes?
View Answer
It separates JavaScript behaviour from HTML structure, supports cleaner organization and allows more flexible event management.
7. What does preventDefault() do?
View Answer
It prevents the default action associated with an event when the event is cancelable.
8. What is the purpose of defer?
View Answer
For external scripts, defer allows the browser to download the script without blocking HTML parsing and executes it after the document has been parsed.
9. Can JavaScript replace HTML and CSS?
View Answer
JavaScript can dynamically manipulate HTML and CSS, but it does not replace their roles. HTML remains the semantic structure and CSS remains the primary presentation layer.
42. Exam Questions
Q1. What is JavaScript used for in an HTML webpage?
Answer
JavaScript is used to add behaviour, logic and interactivity to webpages. It can respond to events, manipulate the DOM, validate forms and communicate with web APIs.
Q2. Write the HTML syntax for linking an external JavaScript file.
Answer
<script src="script.js"></script>
Q3. What is the purpose of the DOM?
Answer
The DOM provides a structured representation of the HTML document that JavaScript can use to access and modify webpage elements.
Q4. Differentiate between textContent and innerHTML.
Answer
textContent inserts or retrieves text content, while innerHTML works with HTML markup inside an element. innerHTML requires care when handling untrusted data.
Q5. Write JavaScript to change the text of an element having the ID "message".
Answer
document.querySelector("#message")
.textContent = "Welcome!";
Q6. Write JavaScript to display an alert when a button is clicked.
Answer
const button =
document.querySelector("#myButton");
button.addEventListener("click", function () {
alert("Button clicked!");
});
Q7. What is the purpose of event.preventDefault() in a form?
Answer
It prevents the browser's default action for the event, such as the normal navigation/submission behaviour of a form, allowing JavaScript to handle the interaction when appropriate.
43. Practical Task — Interactive Registration Page
Build a small interactive course registration page using HTML, CSS and JavaScript.
HTML Requirements
- Create a semantic page structure.
- Add a registration form.
- Include name, email and course fields.
- Add a submit button.
- Create an area for displaying messages.
JavaScript Requirements
- Listen for the form's submit event.
- Prevent default submission for the demonstration.
- Read the entered values.
- Check required information.
- Display a success message.
- Add a CSS class to the success message.
- Clear the form after successful processing.
Advanced Challenge
- Store the selected course in sessionStorage.
- Load course information from a JSON API.
- Display a loading message while data is retrieved.
- Handle API errors gracefully.
- Make the interface keyboard accessible.
44. Quick Revision
| Concept | Remember |
|---|---|
| HTML | Structure and semantics. |
| CSS | Presentation and layout. |
| JavaScript | Behaviour, logic and interactivity. |
| DOM | Programmatic representation of an HTML document. |
| Event | An occurrence to which code can respond. |
| addEventListener() | Registers an event handler. |
| querySelector() | Selects the first matching element. |
| textContent | Reads or sets text content. |
| innerHTML | Reads or sets HTML markup inside an element. |
| classList | Manipulates CSS classes. |
| fetch() | Performs network requests using the Fetch API. |
| localStorage | Stores client-side data persistently. |
| sessionStorage | Stores data for a browser session/tab. |
| defer | Defers execution of an external script until after parsing. |
HTML → Structure | CSS → Style | JavaScript → Behaviour | DOM → Document Representation | Event → User/Browser Action | Listener → Responds to Event | Function → Reusable Logic | API → Application Communication | Fetch → Network Request | classList → CSS State Management