If you want to create a button dynamically, you can use the following code:
document.write("<button id=btn" + i + ">button</button>");
Here are some additional points to consider:
It's important to declare your variables explicitly to avoid implicit globals. You should define the i
variable before using it.
In programming, it is common practice to start counting from 0 instead of 1. So when iterating in a loop, begin with 0
like this:
for (i = 0; i < 10; i = i + 1)
Although it's not mandatory, it is the standard approach in many programming languages.
You can simplify incrementing i
by using ++i
or i++
instead of i = i + 1
:
for (i = 0; i < 10; ++i)
This syntax is more commonly used and considered cleaner.
While document.write
works for small tasks, it's recommended to utilize the DOM manipulation methods for real-world applications. Here's an example using DOM:
var btn = document.createElement("button");
btn.id = "btn" + i;
document.body.appendChild(btn);
I hope these tips help as you continue learning...