Skip to content

Make html table element a link

Joel Meador edited this page Jun 8, 2026 · 1 revision
> Links and html `table` elements don't mix well. How can I make a table row a link? > > Notes: > > each row in the table in created for each item (post) in a list, thus `querySelectorAll` and `.forEach` > > the link path is included in the `data-href` attribute > > `[data-href]` in `querySelectorAll('[data-href]')` grabs elements with that attribute HTML
<%= for post <- @posts do %>
  <tr class="row" data-href="<%= Routes.post_url(@conn,
  :show, post) %>">
    <td class="post-title"><%= post.title %></td>
    <td><%= post.body %></td>
  </tr>
<% end %>
JS
<script>
  var elements = document.querySelectorAll('[data-href]')
  elements.forEach(el =>
    el.addEventListener('click', (e) => {
      var path = el.getAttribute('data-href')
      window.location.assign(path)
    })
  )
</script>

Home

TODO: can we recreate the tag system here roughly with sections about certain subjects?

Clone this wiki locally