how to know if an object is an Html document using javascript

十年热恋 提交于 2019-12-10 19:05:17

问题


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!


回答1:


Try this:

if (obj instanceof HTMLDocument)
{
    // obj is a HTMLDocument
}
if (Object.prototype.toString.call(obj) == "[object HTMLDocument]")
{
    // obj is a HTMLDocument
}



回答2:


You can try this

$obj.is('html')


来源:https://stackoverflow.com/questions/10326889/how-to-know-if-an-object-is-an-html-document-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!