mkrl
mkrl

Reputation: 750

Get element attribute with .each loop

I have a simple example table that has data attributes for every table row.

<table id="example">
  <tr data-sample="1">
    <th>Fox</th>
    <th>Sam</th>
    <th>Ted</th>
  </tr>
  <tr data-sample="2">
    <td>Bill</td>
    <td>Nick</td>
    <td>Pal</td>
  </tr>
  <tr data-sample="3">
    <td>El</td>
    <td>Pal</td>
    <td>Tea</td>
  </tr>
</table>

I'm trying to get all data-sample attributes with the following code:

('#example tr').each(function () {
    console.log(this.data('sample'));
});

JSfiddle

And I'm getting a "this.data is not a function" error. This gets me to the point that in .each jquery loop this returns a DOM element, not a function or whatever I can use a a selector (if I just print out this, I get a list of table rows and their children). Is there any way to get this as a selector? ('#example').children('tr') and ('#example').find('tr') give the same result.

Upvotes: 1

Views: 2435

Answers (4)

Ananth Cool
Ananth Cool

Reputation: 135

Check this

$(document).ready(function(){
            $('#example tr').each(function () {             
                console.log($(this).attr("data-sample"));                   
            });
        });

If you want to get row content use this

$('#example tr').each(function (i) { 
   alert($('#example tr[data-sample]')[i].innerText.split("\t"));
});

Upvotes: 0

Jithin Raj  P R
Jithin Raj P R

Reputation: 6797

There are 2 way to do this -

#1

$('#example tr').each(function () {
  console.log($(this).data('sample'));
});

#2

$('#example tr').each(function () {
  console.log($(this).attr('data-sample'));
});

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82241

There are two issue in you code:

1) you need to convert DOM object to jquery object for using with .data()

2) you are passing wrong property argument in .data(). it should be sample:

$('#example tr').each(function () {
  console.log($(this).data('sample'));
});

Upvotes: 0

prasanth
prasanth

Reputation: 22500

Jquery syntax error

this not jquery object .Do with $(this).data('sample')

$('#example tr').each(function () {
    console.log($(this).data('sample'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have a simple example table that has data-attributes for every table row.

<table id="example">
  <tr data-sample="1">
    <th>Fox</th>
    <th>Sam</th>
    <th>Ted</th>
  </tr>
  <tr data-sample="2">
    <td>Bill</td>
    <td>Nick</td>
    <td>Pal</td>
  </tr>
  <tr data-sample="3">
    <td>El</td>
    <td>Pal</td>
    <td>Tea</td>
  </tr>
</table>

Or do with attr()

  $('#example tr').each(function () {
        console.log($(this).attr('data-sample'));
    });

Upvotes: 2

Related Questions