1 nodeType 节点类型
- nodeType == 1 元素节点
- nodeType == 2 属性节点
- nodeType == 3 文本节点
```
// getAttributeNode() 获取属性节点
// firstChild() 获取第一个子节点
hello world
<a name="6yz3H"></a>
## 2 获取父子兄弟节点
- parentNode
- childNodes
- children
- firstChild firstElementChild lastChild lastElementChild
- previousSibling previousElementSibling
- nextSibling nextElementSibling
```javascript
<ul id="app">
<li>hello world</li>
<li>hello world</li>
<li>hello world</li>
<li>hello world</li>
</ul>
<script>
var app = document.getElementById("app")
var childs = app.childNodes;
console.log(childs); // 所有的子节点 共有9个
var arr = []
for(var i = 0;i<childs.length;i++){
if(childs[i].nodeType == 1){
arr.push(childs[i])
}
}
console.log(arr);
</script>
<ul id="app">
<li>hello world</li>
<li>hello world</li>
<li>hello world</li>
<li>hello world</li>
</ul>
<script>
var app = document.getElementById("app")
console.log(app.children) // 只获取元素节点
</script>
3 增加节点
3-1 appendChild 追加节点(末尾添加节点)
createElement() 创建节点
createTextNode() 创建文本节点
<div id="app">
</div>
<script>
var app = document.getElementById("app")
var p = document.createElement("p")
var txt = document.createTextNode("hello world")
p.appendChild(txt)
console.log(p)
app.appendChild(p)
console.log(app)
</script>
3-2 insertBefore 插入节点
parentNode.insertBefore(newNode,targetNode)
<ul id="app">
<li>html</li>
<li id="js">javascript</li>
</ul>
<!--
innerHtml 元素里的文字
parentNode.insertBefore(newNode,在谁前面) 插入节点
-->
<script>
var app = document.getElementById("app")
var li = document.createElement("li")
var js = document.getElementById("js")
li.innerHTML = "vue"
console.log(li);
app.insertBefore(li,js)
console.log(app)
</script>
3-3 append 在结尾插入节点
3-4 prepend 在开头插入节点
<ul id="app">
<li>html</li>
</ul>
<script>
// append,prepend
var app = document.getElementById("app");
var p1 = "<h1>我是在结尾插入的</h1>";
var p2 = "<h1>我是在开头插入的</h1>"
app.append(p1);
app.prepend(p2)
</script>
3-5 before
3-6 after
<p id="p">hello world</p>
<script>
var p = document.getElementById("p");
p.after("after")
p.before("before")
</script>
4 删除节点
4-1 removeChild() 删除节点
<div id="app">
<div id="child">
hello world
</div>
</div>
<script>
// removeChild() 让元素从DOM树,渲染树中消失
var app = document.getElementById("app")
var child = document.getElementById("child")
app.removeChild(child)
</script>
4-2 remove()
childNode().remove();
5 替换节点
5-1 replaceChild 替换节点
parentNode.replaceChild(newNode,targetNode)
<div id="app">
<div id="child">
child
</div>
</div>
<script>
var app = document.getElementById("app")
var child = document.getElementById("child")
var p = document.createElement("p")
p.innerHTML = "hello world"
app.replaceChild(p,child)
console.log(app);
</script>
6 克隆节点
6-1 cloneNode 克隆节点
node.cloneNode( )
括号为空或false浅拷贝,只复制标签不复制内容
括号为true,深拷贝,也复制内容
<div id="app">
<div id="one">hello world</div>
</div>
<script>
var app = document.getElementById("app")
var one = document.getElementById("one")
var test = one.cloneNode(true)
console.log(test);
app.appendChild(test);
console.log(app);
</script>