Episode 16 of 17
JS-up Your HTML
Add JavaScript to your HTML pages. Learn inline scripts, external JS files, DOM manipulation basics, and making your pages interactive.
JavaScript brings your HTML pages to life. It adds interactivity — button clicks, form validation, dynamic content, animations, and more.
Adding JavaScript to HTML
Method 1: Internal Script
<body>
<h1 id="title">Hello</h1>
<button onclick="changeTitle()">Click Me</button>
<script>
function changeTitle() {
document.getElementById('title').textContent = 'You clicked the button! 🎉';
}
</script>
</body>
Method 2: External Script (Recommended)
<!-- At the bottom of body -->
<script src="app.js"></script>
// app.js
document.getElementById('title').textContent = 'Hello from JS!';
Where to Place Scripts
Place <script> tags at the bottom of the body, just before </body>. This ensures the HTML loads first:
<body>
<!-- All your HTML content -->
<h1>My Page</h1>
<!-- Scripts at the bottom -->
<script src="app.js"></script>
</body>
Or use the defer attribute in the head:
<head>
<script src="app.js" defer></script>
</head>
Basic DOM Manipulation
// Select elements
const heading = document.querySelector('h1');
const buttons = document.querySelectorAll('.btn');
// Change content
heading.textContent = 'New Title';
heading.innerHTML = '<em>Styled Title</em>';
// Change styles
heading.style.color = 'red';
heading.style.fontSize = '3rem';
// Add event listener
heading.addEventListener('click', () => {
alert('You clicked the heading!');
});
JavaScript + HTML is a powerful combination. Once you're comfortable with HTML, JavaScript is the natural next step!