1

I'm trying to loop through table rows, pass in an object, grab each row's data-filter, and check it against the data I'm passing in (key value pairs). My below code isn't grabbing the data-filter value. What am I doing wrong?

HTML

<table id="table">
   <tr data-filter="1">
     <td></td>
   </tr>
   <tr data-filter="2">
     <td></td>
   </tr>
   <tr data-filter="3">
     <td></td>
   </tr>
</table>

JS

$('#table > tr').each(function(data) {
  var $this = $(this);
  var filter = $this.attr(data-filter);
  console.log(filter);
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
codinginnewyork
  • 1,008
  • 2
  • 12
  • 17

1 Answers1

4

One thing to consider, when the code is rendering in browser, browser will automatically added tbody tag inside your table, then this $('#table > tr') selector will failed as this will select direct tr element but right now in the browser the direct child is a tbody though. If you're aware then let continue to the another case is :

$('#table > tbody > tr').each(function(data) {
   var $this = $(this);
   var filter = $this.data('filter'); // or var filter = $this.attr('data-filter');
   console.log(filter);
}
Norlihazmey Ghazali
  • 9,000
  • 1
  • 23
  • 40