I am trying to add multiple elements in a page through a loop in javascript but the code is not running can someone please point out what is wrong
<body>
<script type="text/javascript">
function gengrid()
{
var i=0;
var num_stud=8;
var newdiv;
var divIdName;
for(i=1;i<=num_stud;i++)
{
newdiv = document.createElement('div');
divIdName = '50'+i;
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML ='<img src=50'+i+'.jpg alt="a"></img>';
document.body.appendChild(newdiv);
}
}
</script>
asked Sep 9, 2013 at 17:32
Abhishek Singh
951 silver badge5 bronze badges
3 Answers 3
You have defined a function named gengrid but are not running it. Below the definition of the function, try putting gengrid();.
answered Sep 9, 2013 at 17:35
Cymen
14.5k4 gold badges58 silver badges77 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
I have tested the following code out and it works.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DOM Manipulation</title>
</head>
<body>
<script type="text/javascript">
function gengrid()
{
let num_stud=8;
let newdiv;
let divIdName;
for(let i=1; i<=num_stud; i++)
{
newdiv = document.createElement('div');
divIdName = '50'+i;
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML ='<div id="box'+i+'">Testing 123</div>';
document.body.appendChild(newdiv);
}
}
window.onload = function () {
gengrid();
}
</script>
</body>
</html>
Hope this helps!
Ericksan Pimentel
1822 silver badges11 bronze badges
answered Jun 14, 2016 at 13:41
Tim
1,9062 gold badges28 silver badges48 bronze badges
Comments
If so, be useful to anyone else. I need to create a 4x4 matrix using the canvas tag. To organize it in the right order I put it like this.
let canvas;
let div;
for (let line = 0; line < 4; line += 1) {
div = document.createElement('div');
for (let column = 0; column < 4; column += 1) {
canvas = document.createElement('canvas');
canvas.style.cssText = `
width: 65px;
height: 60px;
border: 1px;
border-color: black;
border-style: solid;
background-color: white;
margin: 5px;
`;
canvas.setAttribute('id', `pallet-${column}.${line}`);
div.appendChild(canvas);
}
main.appendChild(div);
}
answered Feb 13, 2023 at 14:09
Ericksan Pimentel
1822 silver badges11 bronze badges
Comments
default
gengrid()elsewhere?id's are not allowed to start with a number. Thank may be what is causing your problem, but even if it isn't, you need to change that.srcattribute of yourimgtag. Furthermore theimgtag should be self-closing, i.e.<img src="whatever.jpg" alt="a" />.