Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

javascript - JavaScript isDOM —如何检查JavaScript对象是否为DOM对象?(JavaScript isDOM — How do you check if a JavaScript Object is a DOM Object?)

I'm trying to get:(我试图得到:)

document.createElement('div') //=> true {tagName: 'foobar something'} //=> false In my own scripts, I used to just use this since I never needed tagName as a property:(在我自己的脚本中,我以前只是使用它,因为我从来不需要tagName作为属性:) if (!object.tagName) throw ...; So for the second object, I came up with the following as a quick solution -- which mostly works.(因此,对于第二个对象,我想出了以下方法作为一种快速解决方案-大部分都能奏效。) ;)(;)) The problem is, it depends on browsers enforcing read-only properties, which not all do.(问题是,这取决于浏览器是否强制执行只读属性,而并非所有人都这样做。) function isDOM(obj) { var tag = obj.tagName; try { obj.tagName = ''; // Read-only for DOM, should throw exception obj.tagName = tag; // Restore for normal objects return false; } catch (e) { return true; } } Is there a good substitute?(有没有好的替代品?)   ask by Jonathan Lonowski translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This might be of interest:(这可能很有趣:)

function isElement(obj) { try { //Using W3 DOM2 (works for FF, Opera and Chrome) return obj instanceof HTMLElement; } catch(e){ //Browsers not supporting W3 DOM2 don't have HTMLElement and //an exception is thrown and we end up here. Testing some //properties that all elements have (works on IE7) return (typeof obj==="object") && (obj.nodeType===1) && (typeof obj.style === "object") && (typeof obj.ownerDocument ==="object"); } } It's part of the DOM, Level2 .(它是DOM Level2的一部分。) Update 2 : This is how I implemented it in my own library: (the previous code didn't work in Chrome, because Node and HTMLElement are functions instead of the expected object. This code is tested in FF3, IE7, Chrome 1 and Opera 9).(更新2 :这是我在自己的库中实现它的方式:(以前的代码在Chrome中不起作用,因为Node和HTMLElement是函数而不是预期的对象。此代码已在FF3,IE7,Chrome 1和Opera中进行了测试9)。) //Returns true if it is a DOM node function isNode(o){ return ( typeof Node === "object" ? o instanceof Node : o && typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string" ); } //Returns true if it is a DOM element function isElement(o){ return ( typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2 o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName==="string" ); }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...