Creating HTML Elements Dynamically
Change <h1> text after 2 seconds
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Delay</title>
</head>
<body>
<h1 id="heading">Hello Students</h1>
<script>
setTimeout(function() {
document.getElementById("heading").innerText = "Welcome to JavaScript!";
}, 2000);
</script>
</body>
</html>
How it works
1. HTML
<h1 id="heading">Hello Students</h1>
We give the <h1> an id so JavaScript can find it.
2. setTimeout()
setTimeout(function() {
// code
}, 2000);
2000 means 2000 milliseconds = 2 seconds.
3. Change the text
document.getElementById("heading").innerText = "Welcome to JavaScript!";
So the flow is:
Page loads → Wait 2 seconds → Find <h1> → Change its text.