是否是有效的dom节点--轮子代码
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>是否是有效的dom节点</title> <script type="text/javascript"> //是否是节点(body有效) function isNode(elem) { var ts = Object.prototype.toString; var reg = /^(\[object HTML).*?(Element\])$/; var str = ts.call(elem); //IE8下body会识别成[object Object] if (reg.test(str) || (elem !== undefined && elem !== null && elem.nodeName !== undefined && elem.nodeName !== '#text' && elem.nodeName !== '#document')) { return true; } return false; } </script> </head> <body> <ul> <li> 列表节点 </li> </ul> <h4>单测结果输出:</h4> <script type="text/javascript"> //简单测试框架 function test(testArr, expectArr, explain) { var tStr; for (var i = 0, len = testArr.length; i < len; i++) { if(explain && explain[i]){ tStr = explain[i] + ' -> ' + expectArr[i] + ':'; } if (isNode(testArr[i]) === expectArr[i]) { tStr += '成功'; } else { tStr += '失败'; } document.write(tStr + '<br />'); } } // 对验证的说明 var explain; //预期结果 var expect; var ul = document.getElementsByTagName('ul')[0]; var childNodes = ul.childNodes; if (childNodes.length == 3) { expect = [false, true, false]; explain = [ '标准浏览器下childNodes获取的换行文本节点', '标准浏览器下childNodes获取的Dom节点', '标准浏览器下childNodes获取的换行文本节点' ]; } else { expect = [true]; explain = ['IE下childNodes获取的Dom节点']; } test(childNodes, expect, explain); document.write('------------------------<br />'); var testArr = [ document, window, document.body, undefined, null, true, false, '' , 0, 2 / 0, new Number(3), 'str', new String('str'), new String('') ]; expect = [ false, false, true, false, false, false, false, false, false, false, false, false, false, false ]; // 对验证的说明 explain = [ 'document', 'window', 'document.body', 'undefined', 'null', 'true', 'false', '空字符串', '数字0', 'NaN,如2/0', 'new Number(3)', 'str', 'new String("str")', 'new String("")' ]; test(testArr, expect, explain); document.write('------------------------<br />'); //这种变态构造就管不了了 test([ {nodeName: 'DIV'} ], [false]); </script> </body> </html>