-3

I'm new here and look for a way to create multiple elements by using jquery.

Here's an example. I create a table and append a row. How could i include 4 rows more without using createElement?

function table(){
    $(document.createElement("table")).appendTo($('body'))
    $(document.createElement('tr')).appendTo($('table'))
}
  • 3
    Why use this mix `jquery/pure js` ? `$( "body" ).append( "
    " );` instead for example
    – Simone Rossaini Jan 19 '22 at 09:51
  • Alternative if you don't want to build a string is to use `.appendTo` to return the newly appended element `var tbl = $("").appendTo("body"); var tr = $("").appendTo(tbl); cols.forEach(c => tbl.append("
    "))` etc
    – freedomn-m Jan 19 '22 at 10:01
  • Thank you for your answer. it's been usefull and iv'e learnt from it – user17972507 Jan 21 '22 at 07:39

1 Answers1

0

You do not need createElement if you use jQuery

$("body").append(`<table id="table1">
  <thead><tr><th>Header 1</th><th>Header 2</th></thead>
  <tbody>
    <tr><td></td><td></td></tr>
    <tr><td></td><td></td></tr>
    <tr><td></td><td></td></tr>
  </tbody>
</table>`)

Or have a loop:

const rows = Array.from({length:4}).map((_,i) => `<tr><td>Row ${i} Cell 1</td><td>Cell 2</td></tr>`).join("")
$("body").html(`<table><tbody>${rows}</tbody></table>`)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 1
    Thank you. I'm new and started using jquery quiet recently. You solved my question and i learnt something new and easy. – user17972507 Jan 21 '22 at 07:42