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?
$(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>
CodePudding user response:
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>