如何判断一个对象是Element?
群里有个人问这么判断一个对象是Element?
我查了下
//underscore.js的实现
_.isElement = function(obj) {
return !!(obj && obj.nodeType == 1);
};
//valentine.js的实现
, ele: function (el) {
return !!(el && el.nodeType && el.nodeType == 1)
}
//prototype.js的实现
isElement: function(object) {
return object && object.nodeType == 1
}
显然isElement({nodeType:1})这样就不行了
好像没有特别严谨的方法,gg了一下,稍作修改,我的isElement是这样的:
1 <!doctype html> 2 <head> 3 <meta http-equiv="content-type" content="text/html; charset=UTF-8"> 4 <title> </title> 5 </head> 6 <body> 7 <script> 8 var isElement=+'\v1'? 9 function (obj){ 10 return obj instanceof Element 11 }: 12 function (obj){ 13 return obj && obj.nodeType === 1 && obj.tagName !== undefined 14 }; 15 16 //测试 17 if (typeof console==='undefined') { 18 console={ 19 log:function (a){ 20 alert(a); 21 } 22 } 23 } 24 console.log(isElement(document.createElement('a'))); //true 25 console.log(isElement(document.createElement('li'))); //true 26 console.log(isElement(document.createElement('z'))); //true 27 console.log(isElement(document.documentElement)); //true 28 console.log(isElement(window)); //false 29 console.log(isElement({nodeType:1,tagName:2})); //ie true 30 </script> 31 32 </body> 33 </html>