JS 获取第一个和最后一个,子节点、子元素 |
您所在的位置:网站首页 › 获取元素的子元素 › JS 获取第一个和最后一个,子节点、子元素 |
1.获取第一个子元素和子节点
获取第一个子节点 : 父元素.firstChild 获取第一个子元素 : 父元素.firstElementChild //body部分 wwwwww 我是li标签1 我是li标签2 我是li标签3 我是li标签4 我是li标签5 //js部分 var ul = document.getElementById("ul"); console.log(ul.firstChild); console.log(ul.firstElementChild);IE8无法执行元素的操作 IE8兼容性的封装 获取第一个子元素 IE8兼容性的封装 获取第一个子元素 //firstElementChild function getfirstElementChild(ele) { //能力检测 if (ele.firstElementChild != undefined) { // 谷歌火狐 return ele.firstElementChild; }else { // IE8 var nodeFirst = ele.firstChild; while(nodeFirst != null && nodefirst.nodeType != 1){ nodefirst = nodefirst.nextSibling; } return nodefirst; } } console.log(ul.firstElementChild); 2.获取最后一个子元素和子节点获取最后一个子节点 : 父元素.lastChild 获取最后一个子元素 : 父元素.lastElementChild //js部分 //获取元素 var ul = document.getElementById("ul"); console.log(ul.lastChild); console.log(ul.lastElementChild);IE8无法执行元素的操作 IE8兼容性的封装 获取最后一个子元素 IE8兼容性的封装 获取最后一个子元素 //lastElementChild function getlastElementChild(ele) { //能力检测 if (ele.lastElementChild!= undefined) { // 谷歌火狐 return ele.lastElementChild; }else { // IE8 var nodeLast = ele.lastChild; while(nodeLast != null && nodelast.nodeType != 1){ nodelast = nodelast.lastSibling; } return nodelast; } } console.log(ul.lastElementChild); |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |