3

I'm passing an object say, obj, to a function. obj could possibly of any type - (TemplatedHelper, AlertMessage, PartialViews, HTMLDocument, etc.) I want to know if obj is an HTML Document. What are the possible ways to achieve it?

I have tried using

    var containerCount = $(obj).length;
      for (var ctr = 0; ctr < containerCount; ctr++) {
        var containerTagName = $(obj)[ctr].tagName;
        alert(containerTagName); // to know all detected tagNames
                                 // this returns LINK, SCRIPT, DIV, INPUT, etc..                   
        if ((containerTagName == "TITLE") || (containerTagName == "HTML")) {
          var isHTML = true;
          break;
        }
      }

with the preceding code, Chrome only detects the title tag, but IE8 doesn't detect html, head, and title tags. While these fragment codes don't work in IE8 too:

    alert($(obj).has('title')); // or 'html' as element parameter, returns [object Object]
    alert($(obj).find('title')); // or 'html' as element parameter, returns [object Object]
    if ($(obj)[ctr].parent())  
      alert($(obj)[ctr].parent().get(0).tagName); // returns undefined

Please share me your thoughts about it. Thanks in advance!

ideAvi
  • 139
  • 2
  • 3
  • 13
  • An HTML document doesn't necessarily have to have a title tag. – Brad Apr 26 '12 at 03:42
  • 1
    Look at [this](http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object) question and its answers. – annonymously Apr 26 '12 at 03:44
  • @annonymously: `obj` may also be a *PartialView* and it must take a different function than *HTMLDocuments'*. How would it be? – ideAvi Apr 26 '12 at 04:02
  • Use `if (obj instanceof HTMLDocument)` to find out if `obj` is of type `HTMLDocument`. From what I understand, that's what you want. – annonymously Apr 26 '12 at 04:12
  • @Brad: Yup. that's why I've included title tags in all of my HTML Documents ;) only `html`, `head`, and `title` tags make an HTML Document different from PartialViews or did I miss something? – ideAvi Apr 26 '12 at 04:13
  • @annonymously: YES! that's what I want :) but that returns *false*. :( is it possible to select an `html` or `head` tag? – ideAvi Apr 26 '12 at 04:29
  • Are you sure that `obj` *is* a `HTMLDocument`? If it's not then it will obviously return false. – annonymously Apr 26 '12 at 04:42

2 Answers2

9

Try this:

if (obj instanceof HTMLDocument)
{
    // obj is a HTMLDocument
}
if (Object.prototype.toString.call(obj) == "[object HTMLDocument]")
{
    // obj is a HTMLDocument
}
annonymously
  • 4,708
  • 6
  • 33
  • 47
0

You can try this

$obj.is('html')
mprabhat
  • 20,107
  • 7
  • 46
  • 63
  • `obj` is not the tag but the html doc, but I got what you meant. I have to select first the `html` tag before using your answer. Do you have any idea on how to do it? – ideAvi Apr 26 '12 at 04:09