DOM基本操作
节点的类型:
- 元素节点 1
- 属性节点 2
- 文本节点 3
- 注释节点 8
- document 9
- DocumentFragment 11
节点的四个属性:
-
nodeName 元素的标签名,以大小写形式表示,只读
-
nodeValue Text节点或Comment(注释)节点的文本内容,可读写
-
nodeType 该节点的类型,只读
-
attribute 节点的属性集合
节点的一个方法: Note.hasChildNodes();
获取节点
document代表整个文档:
- document.getElementByld()通过元素id获取节点
- document.getElementsByTagName()通过元素标签获取节点
- document.getElementsByName();通过元素的name获取节点
- document…getElementsByClassName()
- document.querySelector//css选择器(在css中怎么选,这里就怎么选),在ie7和ie以下的版本中没有,不是实时的。
- document.querySelectorAll()//css选择器,在ie7和ie以下的版本中没有,不是实时的。
基于节点树的遍历(节点指针):
- parenNote –>获取已知节点的父节点(最顶端的parentNode为#docuemnt);
- childNodes –>获取元素的节点列表
- firstChild —>获取元素的首个子节点
- lastChild —>获取元素的最后一个子节点
- nextSibling —>获取已知节点的后一个兄弟节点
- previousSibling —>获取已知节点的前一个兄弟节点
基于元素节点树的遍历(元素节点指针):
- parentElement–>返回当前元素的父元素节点(IE不兼容)
- children —>返回当前元素子节点
- node.children.length === node.childElementCount 返回当前元素节点数。(IE不兼容)
- firstElementChild—>返回第一个孩子节点(IE不兼容)
- lastElementChild—>返回最后一个孩子节点(IE不兼容)
- nextElementSibling —>返回下一个兄弟元素节点。 (IE不兼容)
- previousElementSibling –>返回前一个兄弟元素节点。(IE不兼容)
节点操作:
- 创建元素节点:document.createElement(元素标签)
- 创建属性节点:document.createAttribute(元素属性)
- 创建文本节点:document.createTextNode(文本文档)
- 向节点的子节点列表的末端添加新的子节点 appenChild(所添加的新节点)
- 在已知子节点前插入一个新的子节点 insertBefore(a,b)在b之前插入a
- 将某个子节点替换为另一个 replaceChild(要插入的新元素,将被替换的老元素)
- 创建指定节点的副本 参数:true:复制当前节点及其所有子节点 false:仅复制当前节点cloneNode(需要被复制的节点.cloneNode(true/false))
- 删除指定的节点 parent.removeChild(父元素删除子节点)
- 删除指定的节点 child.remove(子元素自己删除自己)
属性操作:
- 获取属性 getAttribute(元素节点.getAttribute(元素属性名))
- 设置属性 setAttritube(元素节点.setAttritube(属性名,属性值))
- 删除属性 removeAttritube(元素节点.removeAttritube(属性名))
文本操作:
- insertData(offset,string)从offset指定的位置插入string
- appenData(string)将string插入到文本节点的末尾端
- deleteData(offset,count)从offset起删除count个字符
- replaceData(off,count,string)从off将count个字符用string替代
- splitData(offset)从offset起将文本节点分成两个节点
- substring(offset,count)返回由offset起的count个节点
Dom的基本操作:
1.getElementById方法定义在Document.prototype上,即Element节点上不能使用
2.getElementsByName方法定义在HTMLDocument.prototype上,即非HTMLDocument不能使用
3.getElementsByTagName方法定义在Document.prototype和Element.prtotype上
4.HTMLDocument.prototype定义了一些常用的属性,body,head分别指文档中的<body><head>标签
5.Document.prototype上定义了documentElement属性,指代文档的根元素HTML文档,他总是指代<html>元素
6.getElementsByClassName,querySelector,querySelectorAll在Document.prototype,Element.prototype类中均有定义。
所参照的继承关系:
document --> HTMLDocument.prototype --> Document.prototype