DOM常见方法
getElementById()方法 返回带有指定ID的元素
getElementsByTagName() 返回包含带有指定标签名称的所有元素的节点列表
getElementsByClassName() 返回包含带有指定类名的所有元素的节点列表
appendChild() 把新的子节点添加到指定节点
removeChild() 删除子节点
replaceChild() 替换子节点
insertBefore() 在指定的子节点前面插入新的子节点
createElement() 创建元素节点
createTextNode() 创建文本节点
createAttribute() 创建属性节点
getAttribute() 返回指定的属性值
setAttribute() 把指定属性设置或修改为指定的值
<!-- 案例 -->
<!DOCTYPE html>
<html>
<head>
<title>测试</title>
<meta charset="utf-8">
</head>
<body>
<h1>这是h1标签</h1>
<p>这是p标签</p>
<div class="box" id="box">
<h3>这是box下的h3标签</h3>
<span>hello world!</span>
</div>
<!-- javascript代码 -->
<script type="text/javascript">
// 返回指定id元素
var box = document.getElementById('box');
// 设置边框样式
box.style.border = "1px solid red";
// 创建元素节点
var h4 = document.createElement('h4');
// 设置h4节点内容
h4.innerHTML = "这是h4标签";
// 父元素添加子节点
box.appendChild(h4);
var h3 = box.childNodes[1];
// 删除子节点
box.removeChild(h3);
</script>
</body>
</html>
DOM属性
nodeName属性
nodeName是只读的
元素节点的nodeName 与标签名相同
属性节点的nodeName与属性名相同
文本节点的nodeName始终是#text
文档节点的nodeName始终是#document
nodeValue属性:规定节点的值
元素节点的nodeValue是undefined或null
文本节点的nodeValue是文本本身
属性节点的nodeValue是属性值
nodeType属性:返回节点的类型
<!-- 案例 -->
<html>
<body>
<p id="intro">Hello World!</p>
<script>
//元素节点P
var p = document.getElementById("intro");
var txt= p.innerHTML;//Hello World!
document.write(p.nodeValue+"<br>");//null
document.write(p.nodeName+"<br>");//P
document.write(p.nodeType+"<br>");//1
</script>
</body>
</html>