原生children
首先有几个知识点:
1.获取所有的子集childNodes
2.获取所有子集中的元素节点 curNode.nodeType ===1 nodeType ===2(属性 attr) nodeType ===3(文本 text) nodeType ===8(注释 comments) nodeType ===9(文档 document)
3.将类数组转化为数组 Array.prototype.slice.call(curEle.children)
4.监测数据类型是否为字符串 typeof tagName ==="string"
5.判断标签名是否一样 curNodeEle.nodeName.toloverCase() === tagName.toLowerCase()
<!DOCTYPE html> <html> <head> </head> <body> <div id="box"> <div>1</div> <div>2 <p>12</p></div> <div>3</div> <p>11</p> <p>15</p> </div> <div>4</div> <div>5</div> <div> <p>6</p> <p>7</p> </div> <script src="js/utils.js" type="text/javascript"></script> <script> var box = document.getElementById("box"); //children var ary=[]; function children(curEle,tagName){ if(/MSIE (6|7|8)/i.test(navigator.userAgent)){ var nodeList = curEle.childNodes;//这是获取当前盒子的所有子集 for(var i =0;i<nodeList.length;i++){ var curNode = nodeList[i]; if(curNode.nodeType ===1){//这是获取所有节点中的元素节点 ary.push = curNode; } } }else{ ary = Array.prototype.slice.call(curEle.children);//直接将类数组转化为数组 } if(typeof tagName ==="string"){//检测传进来的类型是否为字符串 for(var k = 0;k<ary.length;k++){ var curNodeEle = ary[k]; if(curNodeEle.nodeName.toLowerCase() !== tagName.toLowerCase()){//传进来的标签是否和里面有的标签一样 ary.splice(k,1); k--; } } } return ary; } console.log(children(box,"p")); </script>