jbehrens94
jbehrens94

Reputation: 2406

JavaScript/jQuery finding string

Let's say I have a table with some data in it, and I want to look for a specific string within tbody, I have got this logic:

if ($('.table--cart tbody tr td')) { ... }

Within the table I check if there is a string str within that td.

if ($('.table--cart tbody tr td')[0].innerHTML.indexOf(str) !== -1)){ ... }

But it doesn't work as expected, when I search in my dev tools for table--cart,it returns not found, but the first check passes,resulting in an error undefined is not an object, evaluating $('.table--cart tbody tr td')[0].innerHTML.indexOf(str) !== -1.

Is my first check wrong? I only want to execute the second check when the first one is true, obviously.

Upvotes: 0

Views: 90

Answers (1)

awimley
awimley

Reputation: 712

Your first check is incorrect.

$('.table--cart tbody tr td')

This will return the jquery prototype. You need to do either:

if ($('.table--cart tbody tr td')[0])

or

if ($('.table--cart tbody tr td').length != 0)

The reason is, a jquery selector like so:

$('#I-dont-exist')

Will still return the jquery prototype, such that you can still call things like parent() on a jquery object whose selector found 0 elements. If you change it to either of the ways I listed above, the first check should be correct. I think your indexOf(str) does not do what you expect, however.

EDIT: Also I think your evaluation should be:

if ( $('.table--cart tbody tr td')[0].html().indexOf(str) !== -1 )

Upvotes: 1

Related Questions