0

Say I have an many html elements, a row in a table composed of table data (<td>) tags.

<td id="data1">foo</td>
<td id="data2">bar</td>
<td id="data3">baz</td>

How would I return the id of the td that was clicked. I know that I should make them links so that I can click on them properly, but just for this case I don't want to put links.

$("td").click(function () {
  id = //The ID finder goes here
  clickFunction(id)
 }

I was thinking this is how it would be formatted. JQuery would attach an onclick event listener to any table data tags and when it fired, a function would run with the id of the table data element that was clicked.

Spaceface16518
  • 101
  • 3
  • 8

2 Answers2

1

Use this code: $(this).attr('id').

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
0

Simply, this.id:

$("td").click(function() {
  console.log(this.id)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td id="data1">foo</td>
    <td id="data2">bar</td>
    <td id="data3">baz</td>
  </tr>
</table>
j08691
  • 204,283
  • 31
  • 260
  • 272
  • I did the **Run code snippet** thing and it just printed out the ID's of all of the `` elements. Is there a reason this is happening? Will it work normally, just not on this code run program? – Spaceface16518 Jan 25 '18 at 02:18
  • @Spaceface16518 What browser are you using? This should log the ID of only the element you clicked, tested in Chrome, Firefox, Edge, and IE 11 – j08691 Jan 25 '18 at 02:24
  • Thanks @j08681, it works with Chrome. On Safari, it just logged all of the ID's of the `td` elements. – Spaceface16518 Jan 25 '18 at 02:38
  • @Spaceface16518 Sounds like Safari's problem (one of the many) – j08691 Jan 25 '18 at 02:40