Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Requesting text from a table row using jquery returns ''

I started using jQuery around a week ago and I wanted to make something like a search from an existing table.

When calling text() from any row it shows and empty string '' making it impossible to compare the searched string to the existing ones in the table.

For example, the following code returns 4 instances of ''. How can I fix this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$(document).ready(() => {
  $('#test tr').filter(() => {
    console.log($(this).text());
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table>
  <tbody id="test">
    <tr>
      <td>example</td>
      <td>1</td>
    </tr>
    <tr>
      <td>example</td>
      <td>2</td>
    </tr>
    <tr>
      <td>example</td>
      <td>3</td>
    </tr>
    <tr>
      <td>example</td>
      <td>4</td>
    </tr>
  </tbody>
</table>

>Solution :

There’s two problems in your code. Firstly you’re using an arrow function so the this keyword will point to the outer context, not the tr element within the iteration. To fix this use an anonymous function, or receive the tr as the argument to the arrow function. I’ve done the latter in the example below.

The second issue is that you’re using filter() as an iterator, which is not correct. filter() should be used to reduce a set of elements within a jQuery object. As you want to loop in this case, you should just use each() instead.

jQuery($ => {
  $('#test tr').each((i, tr) => {
    console.log($(tr).text().trim());
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table>
  <tbody id="test">
    <tr>
      <td>example</td>
      <td>1</td>
    </tr>
    <tr>
      <td>example</td>
      <td>2</td>
    </tr>
    <tr>
      <td>example</td>
      <td>3</td>
    </tr>
    <tr>
      <td>example</td>
      <td>4</td>
    </tr>
  </tbody>
</table>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading