title: Getting the ID of button from an onclick function
body: <p>I currently have sort buttons for each column of a table in my application, and when I click on one of the sort buttons I want the ID of that button to be passed into the function so that the correct column is sorted. In my HTML I simply have a table as such...</p>
  <pre><code>&lt;table id=&quot;table&quot;&gt;&lt;/table&gt;
  </code></pre>
  <p>I then have a few functions that populate the table with all needed rows from the database. For the function that creates the heading row, it will also append a sort button to the end of each cell in that row. I create the sort button through this following method...</p>
  <pre><code>const createSortBtn = item =&gt; {
      let btn = document.createElement(&quot;button&quot;);
      btn.innerHTML = '&amp;#9660;';
      btn.id = item;
      btn.addEventListener(&quot;click&quot;, sortTable);
      return btn;
  }
  </code></pre>
  <p>The variable item is the ID I wish to give the button that is being created, the innerHTML is just a down triangle, and then I also add the onclick function. This onclick function goes as so...</p>
  <pre><code>const sortTable = () =&gt; {
      let order, index = this.id;
      if (document.getElementById(index).innerHTML === '&amp;#9660;') order = &quot;ASC&quot;;
      else order = &quot;DESC&quot;;
      window.sessionStorage.setItem(&quot;order&quot;, order);
      window.sessionStorage.setItem(&quot;index&quot;, index);
      makeSearch();
  }
  </code></pre>
  <p>Most of the function is not too relevant to my question except for the this.id part. From what I have been able to find so far this seems to be the primary method of acquiring the ID of an onclick button (even in strict mode if what I believe is true). However when it is called in the function it is undefined.</p>
  <p>I had been thinking that perhaps I could change the code that when I add the onclick function to the sort button it would go like so...</p>
  <pre><code>const createSortBtn = item =&gt; {
      let btn = document.createElement(&quot;button&quot;);
      btn.innerHTML = '&amp;#9660;';
      btn.id = item;
      btn.addEventListener(&quot;click&quot;, sortTable(item));
      return btn;
  }
  </code></pre>
  <p>...but that seems to call the function immediately which is not the behaviour I wish for.</p>
  <p>I have seen that jQuery seems to have quite a few methods of doing this but I am hoping to stick to native JavaScript if possible. Thanks for all help.</p>