问题
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