0

When I use this code...

var $row = $(this).next("tr[data-control]")

I sometimes get the row I need, but due to siblings, I might also get "prevObject" (in console log).

How do I test for prevObject?

I've tried this...

if ($row == undefined) {}

and this...

if ($row == prevObject) {}

and this...

if ($row == $(this)) {}

But none of those works.

How do I test if my var is prevObject?

Thanks.

Moo-Juice
  • 38,257
  • 10
  • 78
  • 128
MojoDK
  • 4,410
  • 10
  • 42
  • 80
  • 1
    Removed C# tag as it was irrelevant :) – Moo-Juice Sep 09 '13 at 12:46
  • 2
    What you're seeing in the console is just a jQuery object that has a prevObject property. There's no need to test for this ? – adeneo Sep 09 '13 at 12:47
  • @adeno ... well if I do a ... $row.find("tr[data-error]") ... then sometimes I get the data-error row and sometimes I need to go to the parent to find the row ... but I need to figure out when $row.find("tr[data-error]") is returning prevObject and when it returns the row. If it returns the prevObject, then I need to do this ... $row.parent().find("tr[data-error]"). – MojoDK Sep 09 '13 at 13:53
  • I've made a little sample ... http://jsfiddle.net/n2MgS/1 ... I need to test if I have to go to "$(this).parent().next(...". In my jsfiddle sample, I need both data-error divs to show the Error! text – MojoDK Sep 09 '13 at 13:55
  • Add the following inside your `.each` on your fiddle and check the console: `console.log($(this).next('div[data-error]').length ? 'EXIST' : 'DOES NOT EXIST')` – SpYk3HH Sep 09 '13 at 13:59

1 Answers1

4

Generally, if $row = "prevObj" in your console, it means something is wrong in your selection and you're not getting an Element Object. It's not "because of siblings." What you appear to want to check for is "if element exist."

The easiest way to do this is to check length. Such as:

if ($row.length) {
    /* row element exist, do work */
}
else { /* $row element does NOT exist */ }

I answered something similar on another post and even made a plugin. Please see this question and my answer here

jsFiddle

Community
  • 1
  • 1
SpYk3HH
  • 22,272
  • 11
  • 70
  • 81
  • Thanks :) ... So is this the best way to do it ... http://jsfiddle.net/n2MgS/2/ ... ? – MojoDK Sep 09 '13 at 14:01
  • @MojoDK Kind of. Except `if ($row.length == 0)` is not necessary, as this is the same as `if (!$row.length)`, since `0` is interpreted as `false` anyway. – SpYk3HH Sep 09 '13 at 14:03
  • Another tip, try keeping your single tagged elements (like `input`) closed. Example: ``. Note the slash at the end. This ensures better "readability" for both the browser and any "IDE" you might use. – SpYk3HH Sep 09 '13 at 14:07
  • always check if a jquery object exists. checking its length is the way to do this, good answer. – Dave Haigh Sep 09 '13 at 14:13