1

I have Table element and one of the cells carries an Anchor Tag.

I want to get the Text of the Anchor tag of each cell.

i.e. If a Cell has a value as <a href=#>Hello</a> then I want to get the value as Hello

I used to have a dummy DOM by referring to this post:

Here is my working below, but it often gets a blank value or undefined. How can I do this?

JSFIDDLE

$(function() {
  var table = $('#sampleTable').DataTable();


  $('button').click(function() {
    var data = $('#sampleTable').dataTable().fnGetData();

    for (var i = 0; i < data.length; i++) {
      var rVal = data[i][0];
      console.log(rVal);
      //get all child contents
      var el = $('<div/>').html(rVal).contents();
      console.log(el);
      alert(el.find('a').text());
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" rel="stylesheet" />

<table id="sampleTable">
  <thead>
    <tr>
      <th>Col 1</th>
      <th>Col 2</th>
      <th>Col 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><a href=#>R0C1</a></td>
      <td>R0C2</td>
      <td>R0C3</td>
    </tr>
    <tr>
      <td><a href=#>R1C1</a></td>
      <td>R1C2</td>
      <td>R1C3</td>
    </tr>
    <tr>
      <td><a href=#>R2C1</a></td>
      <td>R2C2</td>
      <td>R2C3</td>
    </tr>
  </tbody>
</table>
<button>
Click
</button>
hiFI
  • 1,887
  • 3
  • 28
  • 57

1 Answers1

1

You are already getting a tag i.e : var rVal = data[i][0]; so to get text you can simply use $(rVal).text() or to get text from $('<div/>').html(rVal).contents() you can use el.text().

Demo Code :

$(function() {
  var table = $('#sampleTable').DataTable();


  $('button').click(function() {
    var data = $('#sampleTable').dataTable().fnGetData();

    for (var i = 0; i < data.length; i++) {
      var rVal = data[i][0];
      console.log($(rVal).text());
      //get all child contents
      var el = $('<div/>').html(rVal).contents();
      console.log(el.text());
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" rel="stylesheet" />

<table id="sampleTable">
  <thead>
    <tr>
      <th>Col 1</th>
      <th>Col 2</th>
      <th>Col 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><a href=#>R0C1</a></td>
      <td>R0C2</td>
      <td>R0C3</td>
    </tr>
    <tr>
      <td><a href=#>R1C1</a></td>
      <td>R1C2</td>
      <td>R1C3</td>
    </tr>
    <tr>
      <td><a href=#>R2C1</a></td>
      <td>R2C2</td>
      <td>R2C3</td>
    </tr>
  </tbody>
</table>
<button>
Click
</button>
Swati
  • 28,069
  • 4
  • 21
  • 41