七,DOM
DOM是W3C的标准。定义了操作文档的API规范。
在浏览器中,DOM被实现。通过访问BOM下的window属性下的document的属性,即可操作HTML文档。
1,结构
HTML中,节点大致有三种:标签,标签包含的文本内容,标签的属性。
2,获取节点
getElementById() //返回指定 ID 的元素
getElementsByTagName() //返回指定标签名称的所有元素
getElementsByClassName()//返回指定类名的所有元素
3,节点基本属性
nodeName //节点名,标签为标签名,属性为属性名,标签内部文字则始终为#text
nodeValue //节点值,标签为undefined或null,属性为属性值,标签内部文字则始终为文本本身
nodeType //节点类型,标签为1,属性为2,文本为3
innerHTML //内部html
1> 操作属性
attributes //所有属性的节点列表
getAttribute(attributename) //获取属性值
setAttribute(attributename,attributevalue) //改变属性值
2> 操作子节点
childNodes //节点的所有子节点
node.appendChild(childNode) //添加子节点
node.removeChild(childNode) //删除子节点
node.replaceChild(newnode,oldnode) //替换子节点
node.insertBefore(newnode,existingnode) //在某子节点前添加新子节点
createElement() //创建元素节点。
createTextNode() //创建文本节点。
createAttribute() //创建属性节点。
例子:
<!DOCTYPE html>
<html>
<body>
<div id="parent">
</div>
<script>
var son=document.createElement("div");
var text=document.createTextNode("new child");
son.appendChild(text);
son.setAttribute("id","child");
var parent=document.getElementById("parent");
parent.appendChild(son);
</script>
</body>
</html>