• DOM几种最有用的方法和属性


    1.创建节点

    2.复制节点

    3.插入节点

    4.删除节点

    5.替换节点

    6.查找节点

    7.节点的属性

    8.遍历节点树

    ===========================================

    1.创建节点:

    var p = document.createElement("p");       //创建一个元素节点,新创建出来的元素节点不会被自动添加的奥文档里,它没有nodeParent属性,所以需要用appendChild or insertBefore or 其他方法添加到文档中
    p.setAttribute("title","this is title");       //设置元素节点的属性
    var txt = document.createTextNode("hello world");       //创建一个文本节点
    p.nodeType == 1;
    txt.nodeType ==3;
    p.appendChild(txt);     //将文本节点插入到元素当中
    document.body.appendChild(p);    //将节点添加到文档中

    2.复制节点:

    var new_node = old_node.cloneNode(bool);    //bool 是否连同复制子节点
    //如果bool是true,则也复制子节点,false则只复制本节点,连同本节点属性;复制的新节点也不在文档中,需要数动添加到文档
    
    //例如:
    var old_node = document.createElement("p");
    old_node.setAttribute("id","box");
    old_node.setAttribute("title","this is the title");
    var new_node = old_node.cloneNode(false);
    new_node.setAttribute("id","new_box");     //保证文档中每个节点id的唯一性
    document.body.appendChild(old_node);
    document.body.appendChild(new_node);

    3.插入节点

    <div id="page">
        <div id="header">header</div>
        <div id="navigation">navi</div>
        <div id="footer">footer</div>
    </div>
    var page = document.getElementById("page");
    var header = document.getElementById("header");
    var navi = document.getElementById("navigetion");
    var footer = document.getElementById("footer");
    var content = document.createElement("div");
    content.setAttribute("id","content");
    var txt = document.createTextNode("this is the content");
    content.appendChild(txt);
    //返回的是新节点的引用指针
    //如果target_node 未指定,insertBefore == appendChild
    //referrence = element.insertBefore(new_node,target_node);
    page.insertBefore(content,footer);    //将content插入到footer之前
    page.insertBefore(footer,header)    //将footer从page中删除,然后插入到header之前

    4.删除节点

    reference = element.removeChild(node);

    5.替换节点

    reference = element.replaceChild(new_node,old_node);

    6.查找节点

    element.hasChildNodes    //用来判断该节点是否含有子节点,返回true or false;

    注意:

    TextNode.hasChildNodes    //return false;

    AttrubuteNode.hasChildNodes    //return false;

    7.节点的属性

    nodeName,nodeType,nodeValue

    8.遍历节点树

    element.childNodes

    node.firstChild

    node.lastChild

    node.nextSibling   //求下一个兄弟节点

    node.parentNode  //求父节点

    node.previousSibling  //求前一个兄弟节点

  • 相关阅读:
    网速问题?更换国内源吧!
    NES像素风格的Raspberry
    dalao自动报表邮件2.0
    大佬要我写自动邮件报表系统
    扬帆起航
    Linux下安装与配置tomcat集群+负载均衡
    centos配置ssh和ftp服务
    tomcat中server.xml配置详解
    设置windows 宿主计算机和VMware虚拟机共享文件夹
    Redhat6 yum 安装与配置
  • 原文地址:https://www.cnblogs.com/daxian2012/p/2622155.html
Copyright © 2020-2023  润新知