18-JavaScript DOM的遍历 (04.26)

一.DOM的遍历

1. 父元素查找

    children 返回(元素)子节点
	  console.log(box.children);//HTMLCollection(3) [div.box1, div.box2, ul.list]

childNode 返回子节点(包含文本(空)节点)

	  console.log(box.childNodes);//NodeList(7) [text, div.box1, text, div.box2, text, ul.list, text]

firstChild 返回第一个子节点 (包含文本)

	  console.log(box.firstChild);//#text

firstElementChild 返回第一个子(元素)节点

	  console.log(box.firstElementChild);//div.box1

lastChild 返回最后一个子节点 (包含文本)

	  console.log(box.lastChild);//#text

lastElementChild 返回最后一个子(元素)节点

	  console.log(box.lastElementChild);//ul.list

parentNode 返回父级节点

	console.log(box1.parentNode);//div.box

parentElement 返回父级(元素节点)

	console.log(box2.parentElement);//div.box

offsetParent 相对关系 返回第一个由定位属性的祖元素,如果没有,返回body

	console.log(list1.offsetParent);//body

2.兄弟元素 同胞元素

nextElementSibling 返回下一个兄弟元素节点

console.log(box1.nextElementSibling);

nextSibling 返回下一个兄弟节点 包含文本

console.log(box1.nextSibling);

nextElementSibling 返回上一个兄弟元素节点

console.log(box2.previousElementSibling);

nextSibling 返回上一个兄弟节点 包含文本

console.log(box1.previousSibling);

二、DOM节点的增删改查

创建元素

var arr1=document.createElement('P')
arr1.innerText='段落标签6';
arr1.style.backgroundColor='yellow'
var arr2=document.createElement('P')
arr2.innerText='段落标签7';
arr2.style.backgroundColor='hotpink'
var arr3=document.createElement('P')
arr3.innerText='段落标签8';
arr3.style.backgroundColor='lightblue'

插入元素

	      aBtn.insertBefore(arr2,aBoxs[1])

替换元素

	      aBtn.replaceChild(arr3,aBoxs[4])

删除元素

	     aBtn.removeChild(aBoxs[3])

版权声明:本文为weixin_69290586原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。