0
Storing reference to elements. Js Html
Hello all. I am assigning elements to an html document using a for loop. var table; for(var idnum=1; idnum < 8; idunm++){ table += '<p id= _____ >'+'</p>'; document.write('<table>'+ table+'</table>'); How Can I assign a variable like 'idnum' as a part of the id attribute parameter? for example: id = "row"+idnum I tried, but with no success.
4 odpowiedzi
+ 7
var table;
for(var idnum=1; idnum < 8; idunm++){
table += '<p id="'+idnum+'">'+'</p>';
document.write('<table>'+ table+'</table>');
+ 7
^ tried this? ^
should result in
'<p id="1"></p>'
+ 5
// First, you need to initialize with empty string:
var table = '';
// Next, you have to correctly build the <table> structure ( with at least <tr> and <td> ):
var idnum = 0; // init the idnum outside the nested loop
var hsize = 2; // set number of rows ( height size )
var wsize = 3; // set number of cells ( width size )
// number of idnum will be wsize * hsize == 6 ( instead 7 in your example :P )
for (var row=0; row < hsize; row++) {
table += '<tr>';
for (var cell=0; cell < wsize; cell++) {
// you can calculate here the actual idnum:
// idnum = 1 + cell + ( row * wsize );
// or just increment it ( for start from 1, require to initialize to 0 if incrementation at begin of loop, to 1 if at loop end...
idnum++;
table += '<td>'; // I keep your data example with id attributed to <p>, but you could set the one of <td>
table += '<p id="mytable'+idnum+'">'; // prepend a name to your number id
// here add some content to your <p>:
table += 'Some content to be in the paragraph of cell #'+idnum;
// and close the <td>
table += '</td>';
}
// close <tr>
table += '</tr>';
}
// now you can output your html <table> code:
document.write('<table>'+ table+'</table>');
// But you could have initialized your 'table' variable with the <table> opening tag, and just finally append the closing one:
var table = '<table>';
/* same nested loops */
document.write(table+'</table>');
+ 1
Thank you guys, works Great!