0

I am creating a table with elements from a database. I am using this function to render the elements in the HTML

function tableToHTML(tableData) {
var table = document.createElement('table'), 
tableBody = document.createElement('tbody');

tableData.forEach(function(rowData) {
    var row = document.createElement('tr');

    rowData.forEach(function(cellData) {
        var cell = document.createElement('td');
        cell.appendChild(document.createTextNode(cellData));
        row.appendChild(cell);
    });

    tableBody.appendChild(row);
});

table.appendChild(tableBody);
document.body.appendChild(table);

}

Can I somehow assign id or class attributes to the created trs or tds within the javascript? I am using the Meteor framework, so jQuery is fair game if it is simpler to do with jQuery.

Steve C
  • 527
  • 1
  • 3
  • 14

2 Answers2

0

You can assign a class using .className = 'class', and an ID using .id = 'ID':

var elem = document.createElement('td')
elem.className = 'myClass'
elem.id = 'myId'

This will result in an element like so:

<td id="myId" class="myClass"></td>

You can also use jQuery's .addClass to add a class, and .attr for the ID (check the answer here)

Community
  • 1
  • 1
Kaspar Lee
  • 5,446
  • 4
  • 31
  • 54
0

In jQuery you can create an object and assign attributes to it all in one call, by supplying the attributes in an object argument.

var cell = $("<td>", {
    "class": "myClass",
    "id": "myId"
});
Barmar
  • 741,623
  • 53
  • 500
  • 612