开发者

Determining if an object is a <div> or a window

as far as I can see, it is possible to verify in JavaScript that a certain object is actually a div element:

if (element.constructor  == HTMLDivElement) {
  //...
}

How can I apply a similar check to see if the element is a window? Checking against DOMWindow doesn't work, such a function appears to be und开发者_运维百科efined.


The "tagName" attribute of a DOM element will tell you what sort of DOM element it is. I don't know of any good way to check to see if a reference is to a "window" instance other than by duck-typing.

Rather than check to see what a reference is, perhaps you should be checking to see what the object can do, or appears to be able to do. What exactly are you trying to accomplish by determining the nature of an object?

Because Javascript objects are so malleable, even if you determine an object is a <div> DOM instance doesn't necessarily tell you everything about it, because code may have altered the properties of the object beyond recognition.


If you only need to check whether the object is the current browser window (as opposed to another browser window), you can do this very easily with a simple identity check with the window object (so long as you haven't over-ridden it).

if (obj === window) {
    // it's your window
} else if (obj.nodeName && (obj.nodeName.toLowerCase() === 'div')) {
    // it's a div
} else {
    // it's something else
}


From the jQuery source comes one solution:

// A crude way of determining if an object is a window
function isWindow ( obj ) {
    return obj && typeof obj === "object" && "setInterval" in obj;
}


With jquery it should be as simple as If ($('div').length == 0) { //their are no divs }else{ //their is div on the page }

You could also check if an id or class exists

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜