JavaScript基礎 -- 常見DOM樹操作
阿新 • • 發佈:2017-10-13
tle rep Language ron -s name 增加 lan scrip
1.創建並增加元素節點
<ul id="ul">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<script>
var parentElement = document.getElementById("ul");
var NewNode= document.createElement("li");
NewNode.innerText="AddNode";
parentElement.appendChild(NewNode);
</script>
2.判斷是否存在子節點
<ul id="ul">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
- <ol id="ol"></ol>
<script>
var parentElement = document.getElementById("ul");
var parentElement2 = document.getElementById("ol");
if(parentElement.hasChildNodes()) {
alert("<ul>有子節點");
}
if(parentElement2.hasChildNodes()) {
alert("<ol>有子節點");
}
</script>
3.新建節點插入指定子節點的前面
<ul id="ul">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<script>
var parentElement = document.getElementById("ul");
var secondNode = parentElement.getElementsByTagName("li")[1];
varNewNode = document.createElement("li");
NewNode.innerText = "insertNode";
parentElement.insertBefore(NewNode, secondNode); //將NewNode插入在secondNode前面
</script>
4.替換子節點
<ul id="ul">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<script>
var parentElement = document.getElementById("ul");
var secondNode = parentElement.getElementsByTagName("li")[1];
varNewNode = document.createElement("li");
NewNode.innerText = "replaceNode";
parentElement.replaceChild(NewNode, secondNode); //將secondNode替換成NewNode
</script>
5.刪除指定節點
<ul id="ul">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<script>
var parentElement = document.getElementById("ul");
var secondNode = parentElement.getElementsByTagName("li")[1];
parentElement.removeChild(secondNode);
</script>
JavaScript基礎 -- 常見DOM樹操作