0
$.fn.foo = function() {
    console.log($(this));
};

$("#foo").foo();

$(document).foo();

How can I tell weather $(this) inside the function is $(document) or not?


In this question, people suggested

1. if (obj instanceof HTMLDocument)

2. if (Object.prototype.toString.call(obj) == "[object HTMLDocument]")

3. $obj.is('html')

but none of them works.

Community
  • 1
  • 1
user1643156
  • 4,407
  • 10
  • 36
  • 59

2 Answers2

9

What about simple...

if (this[0] === document)

... as this inside jQuery function corresponds to jQuery object (not HTML one). Even if this object is empty, this[0] is still a valid expression - it's just undefined.

An alternative is to use jQuery is method:

if ($(this).is(document))

... as it accepts DOMElement as a param too.

raina77ow
  • 103,633
  • 15
  • 192
  • 229
  • 1
    +1 saw you had the right answer so I waited.. but `this` doesn't need to be wrapped if it's inside the jQuery function – wirey00 Mar 22 '13 at 14:34
0
$.fn.foo = function() {
    console.log(this[0] == document);
};

$("#foo").foo();

$(document).foo();
waney
  • 402
  • 1
  • 5
  • 20