mercredi 27 janvier 2021

Proper way to get an attribute of an DOM element using jQuery [duplicate]

I am new to jQuery. I am trying to get the attribute value of a tag inside a table but it is returning "undefined".

HTML skeleton

<table class="table" id="restaurant-table">
      <thead></thead>
      <tbody></tbody>
</table>

Using Lodash template and fetching from an API, I am populating the tbody with some tr tags:

const tableRows = _.template(`
  <% restaurants.forEach((restaurant) => { %> 
    <tr data-id="<%- restaurant._id %>">
        <td><%- restaurant.name %></td>
        <td><%- restaurant.cuisine %></td>
        <td><%- restaurant.address.building %> <%- restaurant.address.street %></td>
        <td><%- avg(restaurant.grades) %></td>
    </tr>
  <% }) %>
`);

However, when wiring up the event for the tr tags, I cannot get the "data-id" attribute of it.

$(() => {
  $("#restaurant-table tbody").on("click", "tr", (e) => {
      let id = $(this).data("id");            // returns "undefined"
      //let id = $(this).attr("data-id");     // also returns "undefined"
      console.log(id);
  });
});

I think I am selecting the wrong element with $(this) but I am not sure what to change. Is there any better way to this?




Aucun commentaire:

Enregistrer un commentaire