0

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.

3
  • 3
    You might want to use :contains() for this issue. api.jquery.com/contains-selector Commented Oct 27, 2015 at 12:48
  • 1
    try using $('.table--cart tbody tr td').first().has(str) also the $ should come before ('.table--cart ... Commented Oct 27, 2015 at 12:50
  • 1
    You use jQuery to get your element, but jQuery doesn't have a method innerHTML, you can try html instead. Commented Oct 27, 2015 at 12:56

1 Answer 1

1

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 )
Sign up to request clarification or add additional context in comments.

1 Comment

I believe that length is not a function ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.