JavaScript Basics-Common DOM tree operations

Source: Internet
Author: User

1. Create and add ELEMENT nodes

  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. Determine if a child node exists

  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. New node inserted in front of the specified child node
  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. Replacing child nodes
  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. Delete the specified node
  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 Basics-Common DOM tree operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.