1. 程式人生 > >JavaScript基礎 -- 常見DOM樹操作

JavaScript基礎 -- 常見DOM樹操作

tle rep Language ron -s name 增加 lan scrip

技術分享

1.創建並增加元素節點

  1. <ul id="ul">
  2. <li>1</li>
  3. <li>2</li>
  4. <li>3</li>
  5. </ul>
  6. <script>
  7. var parentElement = document.getElementById("ul");
  8. var NewNode= document.createElement("li");
  9. NewNode.innerText="AddNode";
  10. parentElement.appendChild(NewNode);
  11. </script>

2.判斷是否存在子節點

  1. <ul id="ul">
  2. <li>1</li>
  3. <li>2</li>
  4. <li>3</li>
  5. </ul>
  6. <ol id="ol"></ol>
  7. <script>
  8. var parentElement = document.getElementById("ul");
  9. var parentElement2 = document.getElementById("ol");
  10. if(parentElement.hasChildNodes()) {
  11. alert("<ul>有子節點");
  12. }
  13. if(parentElement2.hasChildNodes()) {
  14. alert("<ol>有子節點");
  15. }
  16. </script>

3.新建節點插入指定子節點的前面
  1. <ul id="ul">
  2. <li>1</li>
  3. <li>2</li>
  4. <li>3</li>
  5. </ul>
  6. <script>
  7. var parentElement = document.getElementById("ul");
  8. var secondNode = parentElement.getElementsByTagName("li")[1];
  9. varNewNode = document.createElement("li");
  10. NewNode.innerText = "insertNode";
  11. parentElement.insertBefore(NewNode, secondNode); //將NewNode插入在secondNode前面
  12. </script>

4.替換子節點
  1. <ul id="ul">
  2. <li>1</li>
  3. <li>2</li>
  4. <li>3</li>
  5. </ul>
  6. <script>
  7. var parentElement = document.getElementById("ul");
  8. var secondNode = parentElement.getElementsByTagName("li")[1];
  9. varNewNode = document.createElement("li");
  10. NewNode.innerText = "replaceNode";
  11. parentElement.replaceChild(NewNode, secondNode); //將secondNode替換成NewNode
  12. </script>

5.刪除指定節點
  1. <ul id="ul">
  2. <li>1</li>
  3. <li>2</li>
  4. <li>3</li>
  5. </ul>
  6. <script>
  7. var parentElement = document.getElementById("ul");
  8. var secondNode = parentElement.getElementsByTagName("li")[1];
  9. parentElement.removeChild(secondNode);
  10. </script>

JavaScript基礎 -- 常見DOM樹操作