1、获取节点
节点和元素节点
firstChild() 获取第一个子节点lastChild() 获取最后一个子节点childNodes 获取所有子节点children 获取所有子元素节点parentNode 获取父节点firstChild 获取第一个子节点firstElementChild 获取第一个元素子节点lastChildlastElementChildnextSibling 前一个节点nextElementSibling 前一个元素节点previousSiblingpreviousElementSibling
<ul id="app"><li>html</li><li>css</li></ul><script>var app = document.getElementById("app")console.log(app.firstElementChild);</script>
1-1 nodeType 节点类型
- nodeType == 1 元素节点
- nodeType == 2 属性节点
- nodeType == 3 文本节点
<p id="app">hello world</p><script>/* 节点的类型 nodeType元素节点 1属性节点 2文本节点 3*/var app = document.getElementById("app");var app_id = app.getAttributeNode("id");var txt = app.firstChild;console.log(app.nodeType);console.log(app_id.nodeType);console.log(txt.nodeType)</script>
getAttributeNode() 获取属性节点
``` // getAttributeNode() 获取属性节点 // firstChild() 获取第一个子节点<h1>我是在开头插入的</h1>hello worldhello world<h1>我是在结尾插入的</h1>
- hello world
- hello world
- hello world
- hello world
- hello world
- hello world
- hello world
- hello world
child
one
middle
two
```
# 2、增加节点
## 2-1 appendChild 追加节点(末尾添加节点)
**向节点的子节点列表的末尾添加新的子节点**
```
createElement() 创建元素节点
createTextNode() 创建文本节点
createAttribute()创建属性节点
```
### appendChild -->只能添加节点(Node)
### append -->可以添加节点和字符串
```
**在已有的子节点前插入一个新的子节点**
**innerHTML 元素里的文字** ```
- html
- javascript
- html
//prepend —在父元素的最前面插入节点
<a name="U2e3b"></a>## 2-5 before<a name="stedm"></a>## 2-6 after
hello world
<a name="Pfrsc"></a># 3、删除节点<a name="rJzch"></a>## 3-1 removeChild() 删除节点
hello world
<script>// removeChild() 让元素从DOM树,渲染树中消失var app = document.getElementById("app")var child = document.getElementById("child")app.removeChild(child)</script>// removeChild 从父节点上删除某个子节点parentElment.removeChild(childElement)
<a name="ilbGs"></a># 4、替换节点<a name="IMfmd"></a>## 4-1 replaceChild 替换节点`parentNode.replaceChild(newNode,targetNode) 替换某个元素`
child
<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>
<a name="yCidn"></a># 5、克隆节点<a name="sQpTE"></a>## 5-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>
