skip to Main Content

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


  1. 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:

    "Why You Shouldn’t Use Class Selectors In JavaScript
    "

    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.

    const result = {
      data: [
        { id: 1, firstName: 'John', lastName: 'Doe', jobTitle: 'Executive', email: '[email protected]' },
        { id: 2, firstName: 'Mary', lastName: 'Allen', jobTitle: 'Manager', email: '[email protected]' },
        { id: 3, firstName: 'Frank', lastName: 'Rodgers', jobTitle: 'Clerk', email: '[email protected]' }
      ]
    };
    
    // Map each data entry to a table row element containing all the proper cells
    $("#personnelTable > tbody").append(result.data.map(createRow));
    
    function createRow({ id, firstName, lastName, jobTitle, email }) {
      return `
        <tr>
          <td class="align-middle text-nowrap" scope="row" data-field="name">
            ${firstName} ${lastName}
          </td>
          <td class="align-middle text-nowrap d-none d-md-table-cell" data-field="jobTitle">
            ${jobTitle}
          </td>
          <td class="align-middle text-nowrap d-none d-md-table-cell" data-field="email">
            ${email}
          </td>
          <td>
            <button type="button"
                class="btn btn-primary btn-sm editPersonnelBtn"
                data-bs-toggle="modal"
                data-bs-target="#editPersonnelModal"
                data-id="${id}"
                title="Edit">
              <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="${id}"
                title="Remove">
              <i class="fa-solid fa-trash fa-fw"></i>
            </button>
          </td>
        </tr>
      `;
    }
    td[data-field="name"]     { color: red !important;   }
    td[data-field="jobTitle"] { color: green !important; }
    td[data-field="email"]    { color: blue !important;  }
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.2/css/bootstrap.min.css" rel="stylesheet"/>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" rel="stylesheet"/>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.2/js/bootstrap.min.js"></script>
    <div class="container">
      <table id="personnelTable" class="table table-striped">
        <thead>
          <tr>
            <th scope="col">Name</th>
            <th scope="col">Job Title</th>
            <th scope="col">Email</th>
            <th scope="col">Actions</th>
          </tr>
        </thead>
        <tbody class="table-group-divider"></tbody>
      </table>
    </div>
    Login or Signup to reply.
  2. I’m sorry but I think your code is little confusing.
    I add sample code below.

    const { firstName, lastName, jobTitle, email, id } = result.data[0];
    const $table = $("#personnelTable");
    
    const createTableCell = (content, classes = "", customClass = "") =>
      `<td class="${classes} ${customClass}">${content}</td>`;
    
    $table.append(`
      <tr>
        ${createTableCell(`${firstName} ${lastName}`, "align-middle text-nowrap")}
        ${["lastName", "jobTitle", "email"].map((prop) =>
          createTableCell(
            eval(prop),
            `align-middle text-nowrap d-none d-md-table-cell`,
            prop
          )
        )}
        <td>
          <button type="button" class="btn btn-primary btn-sm editPersonnelBtn" data-bs-toggle="modal" data-bs-target="#editPersonnelModal" data-id=${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=${id}>
            <i class="fa-solid fa-trash fa-fw"></i>
          </button>
        </td>
      </tr>
    `);
    
    

    You can add custom class for name ,jobTitle ,email, by defining each class.

    Login or Signup to reply.
  3. It can be done simply adding these lines after append:

    $("#personnelTable").append(markup).children('tr').children('td:first-child').addClass('class1 class2 class3')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search