zoukankan      html  css  js  c++  java
  • 常用dom方法封装

    // 封装一个方法能够在元素后面插入dom元素 (在原型链上编程)
     
    <div>
        <span></span>
        <p></p>
        <strong></strong>
        <i></i>
        <address></address>
    </div>
    

      

     
    Element.prototype.insertAfter=function(targetNode,afterNode){
        var beforeNode=afterNode.nextElementSibling;
       if(beforeNode==null){
             this.appendChild(targetNode)
        }else{
          this.insertBefore(targetNode,beforeNode);
        } 
    }
    
    
    var div=document.getElementsByTagName('div')[0];
    var strong=document.getElementsByTagName('strong')[0];
    var p=document.getElementsByTagName('p')[0];
    var ul=document.createElement('ul');
    
    div.appendChild(ul)
    Element.prototype.insertAfter=function(targetNode,afterNode){
      var beforeNode=afterNode.nextElementSibling;
      if(beforeNode==null){
        this.appendChild(targetNode)
      }else{
        this.insertBefore(targetNode,beforeNode);
      } 
    }
    
    var li=document.createElement('li');
    div.insertAfter(li,strong)
    // 遍历元素节点树(在原型链上编程)
    var a=[];
    Element.prototype.allElements=function(){
              
              var dom=this
              for(var i=0;i<dom.children.length;i++){
                  a.push(dom.children[i])
                  if(dom.children[i].hasChildNodes()){
                      // console.log(this.children[i].children[i])
    
                       dom.children[i].allElements();
                  }
                   
                   
              }
           return a;
    
        }
    
    console.log(div.allElements())
     
  • 相关阅读:
    html 注释和特殊字符
    html 锚点链接
    html 链接标签
    spring 利用工厂模式解耦
    html 路径
    html 图像标签
    html div和span标签
    html 文本格式化标签
    P5358 [SDOI2019]快速查询
    luoguP2679 子串
  • 原文地址:https://www.cnblogs.com/h5it/p/13456521.html
Copyright © 2011-2022 走看看