遍历节点树
- parentNode 父节点(最顶端的parentNode为#document)
- childNodes 子节点们
- firstChild 第一个子节点
- lastChild 最后一个子节点
- nextSibling 后一个兄弟节点,previousSibling前一个兄弟节点
节点的四个属性
- nodeName
元素的标签名、以大写形式表示,只读 - nodeValue
text节点或comment节点的文本内容,可读写 - nodeType
该节点的类型,只读(返回数字) - attributes
Element节点的属性集合 用法(div.attribute)可以进行读写,但是一般不进行写,用getAttribute()更适合
节点的一个方法 hasChildNodes();
节点的增删改查
增:
- document.createElement(’’);创建元素节点
- document.createTextNode(’’)创建文本节点
- document.createComment(’’)创建注释节点
- doucment.createDocumentFragment()创建碎片节点
插:
- parentNode.appendChild();----document.body.appendChild(插入页面)—任何一个节点都有appendChild方法,类似push。
- parentNode.insertBefore(a, b)
删:
- parent.removeChild()谋杀(剪切)
- child.remove()自尽-----不填参数且不具备剪切
替换:
- parent.replaceChild(new, origin)
基于元素节点树的遍历
- parentElement 返回当前元素的父元素节点
- children 只返回当前元素的元素子节点
- node.childElementCount === node.children.length 当前元素节点的子元素
- first ElementChild 返回的是第一个元素节点(IE不兼容)
- astElementChild 返回的是最后一个元素节点 除了children在IE兼容,其他的只能在IE9上兼容
- next ElementSibling
这个函数是模仿children方法
function retElementChild(node) {
// 这是个类数组
var temp = {
length : 0,
push : Array.prototype.push,
slice : Array.prototype.slice
},
child = node.childNodes,
len = child.length;
for(var i = 0; i < len; i ++) {
if(child[i].nodeType === 1){
temp.push(child[i]);
}
}
return temp;
}
Element节点的属性
- innerHTML 取值、写值(覆盖)
- innerText 取出文本内容,但是若有其他结构就不能乱写,否则会覆盖已有结构(火狐不兼容,同样作用(textContent老版本IE不兼容))
Element节点的一些方法
- ele.setAttribute()
例子 div.setAttribute(‘class’, ‘demo’); - ele.getAttribute()
例子 div.getAttribute(“class”); - ele.className()
拓展
document:
document.compatMode检验是标准还是怪异模式
举个例子,继承之间的关系
document—>HTMLDocument.prototype—>Document.prototype
- getElementById方法定义在Document.prototype上,即Element节点上不能使用
- getElementsByName方法定义在HTMLDocument.prototype上,即非html document不能使用(如xtml document.Element)
- getElementsByTagName方法定义在Document.prototype和Element.prototype
- HTMLDocument.prototype定义了一些常用的属性、body、head分别指文档中的(document.body document.head)
- Document.prototype上定义了documentElement属性,指代文档的根元素HTML文档中(document.documentElement—>html)
- getElementsByClassName、querySelectorAll、querySelector在Document.prototype Element.prototype中均有定义
封装nextElementSibling和preElementSibling方法
function retSibling(e, n) {
while(e && n) {
if(n > 0) {
if (e.nextElementSibling) {
e = e.nextElementSibling
} else {
for( e = e.nextSibling; e && e.nodeTpye != 1;e = e.nextSibling) {}
}
n --
} else {
if (e.previousElementSibling) {
e = e.previousElementSibling
} else {
for(e = e.previousSibling; e && e.nodeTpye != 1; e = e.previousSibling) {}
}
n ++
}
}
return e
}