-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
  • 3
    Why use this mix jquery/pure js ? $( "body" ).append( "<table><tr></tr><tr></tr><tr></tr><tr></tr></table>" ); instead for example Commented Jan 19, 2022 at 9:51
  • Alternative if you don't want to build a string is to use .appendTo to return the newly appended element var tbl = $("<table>").appendTo("body"); var tr = $("<tr>").appendTo(tbl); cols.forEach(c => tbl.append("<td>")) etc Commented Jan 19, 2022 at 10:01
  • Thank you for your answer. it's been usefull and iv'e learnt from it Commented Jan 21, 2022 at 7:39

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I'm new and started using jquery quiet recently. You solved my question and i learnt something new and easy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.