I have dynamically created a table and I want to add three different classes for the first <td>
for first and last name, job title and email.
I have tried to use classes for each of the corresponding <td>
but to no avail. Any help would be appreciated.
var markup = "";
markup += '<tr>';
markup += '<td class="align-middle text-nowrap">' + result.data[0].firstName + result.data[0].lastName + '</td>';
markup += '<td class="align-middle text-nowrap d-none d-md-table-cell">' + result.data[0].jobTitle + '</td>';
markup += '<td class="align-middle text-nowrap d-none d-md-table-cell">' + result.data[0].email + '</td>';
markup += '<td><button type="button" class="btn btn-primary btn-sm editPersonnelBtn" data-bs-toggle="modal" data-bs-target="#editPersonnelModal" data-id = '+result.data[0].id+'> <i class="fa-solid fa-pencil fa-fw"> </i></button><button type="button" class="btn btn-primary btn-sm deletePersonnelBtn" data-bs-toggle ="modal" data-bs-target="#deletePersonnelModal" data-id= '+ result.data[0].id+ '> <i class="fa-solid fa-trash fa-fw"></i> </td>';
markup += '</tr>';
$("#personnelTable").append(markup);
HTML
<table id="personnelTable">
</table>
3
Answers
You can use template literals to build the HTML content. This is way easier to understand the output HTML.
Now for your question, I would not use a class at all in the situation. I would use a data attribute that describes what the cell represents. You do not necessarily want to style the cell, more than you want to describe it.
Also, with classes; you can get confused between presentation and semantic meaning. Data attributes are clearer and represent a more lexical understanding of the data presented.
The following article contains some great scenarios for data attribute usage:
Note: You may need to open the result in a full screen to see all the column data. Bootstrap will condense what is displayed at smaller resolutions.
I’m sorry but I think your code is little confusing.
I add sample code below.
You can add custom class for
name
,jobTitle
,email
, by defining each class.It can be done simply adding these lines after append: