javascript - Determining if an object is a <div> or a window - Stack Overflow

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

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 undefined.

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 undefined.

Share Improve this question asked Nov 17, 2010 at 13:38 dpqdpq 9,29812 gold badges53 silver badges71 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

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 acplish 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 es 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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745063704a4609124.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信