I want to create a bunch of buttons in the html body based on an array stored in Javascript. Here is my code:
<!DOCTYPE>
<html>
<head>
<script>
var listBrand =['LEXUS','AUDI','MAYBACK','FERRARI','TOYOTA'];
//the array
function printBtn() {
for (var i = 0; i < listBrand.length; i++) {
var btn = document.createElement("button");
var t = document.createTextNode(listBrand[i]);
btn.appendChild(t);
document.body.appendChild(btn);
}
}
</script>
</head>
<body>
<div onload="printBtn();">
</div>
</body>
</html>
I want to have all 5 buttons LEXUS
, AUDI
, MAYBACK
, FERRARI
, and TOYOTA
show up in the body when the page loads, but the buttons fail to appear.
Is there anything wrong with my code? Any help and/or explanations are appreciated. Thank you.
JavaScript does not provide the multidimensional array natively. However, you can create a multidimensional array by defining an array of elements, where each element is also another array. For this reason, we can say that a JavaScript multidimensional array is an array of arrays.
Array Elements Can Be Objects JavaScript variables can be objects. Arrays are special kinds of objects. Because of this, you can have variables of different types in the same Array.
Nested Array in JavaScript is defined as Array (Outer array) within another array (inner array). An Array can have one or more inner Arrays. These nested array (inner arrays) are under the scope of outer array means we can access these inner array elements based on outer array object name.
The onload
event can only be used on the document/body
, frames
, images
, and scripts
.
It can be attached to only body and/or each external resource. The div
is not an external resource, so the onload
event doesn't apply there.
Use following:
<body onload="printBtn();">
Instead of
<div onload="printBtn();">
And you are good to go.
Maybe you should take a look at window.onload vs document.onload here on SO too.
I believe the problem is that the div
element doesn't have an onload
event.
You should bind the printBtn
method to the window.onload
event instead.
I created a working jsfiddle for you to see : https://jsfiddle.net/5rq60y0u/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With