DOM 增删改查

添加元素,子元素(子元素,文本),属性

window.dom={};
window.dom.create = function (tagName,children,attributes) {
    var tag = document.createElement(tagName);
    if(typeof children === 'string'){
        var text =document.createTextNode(children);
        tag.appendChild(text);
    }else if(children instanceof HTMLElement){
        tag.appendChild(children)
    } else if(children instanceof Array){
        for(var i=0;i<children.length;i++){
            if(typeof children[i] === 'string'){
                tag.appendChild(document.createTextNode(children[i]))
            }else if(children[i] instanceof HTMLElement){
                tag.appendChild(children[i])
            }
        }
    }
    if (typeof attributes === 'object'){
        for(var key in attributes){
            tag.setAttribute(key,attributes[key])
        }
    }
    return tag;
};

删除元素的所有子元素

window.dom.empty = function(tagName){
    var firstChild = tagName.childNodes[0];
    while(firstChild){
        firstChild.remove();
        firstChild = tagName.childNodes[0];
    }
};

改变元素的属性

window.dom.attr = function(tagName,attributes){
    for(var key in attributes){
        tagName.setAttribute(key,attributes[key]);
    }
    return tagName;
};

window.dom.style = function(tagName,styles){
    for(key in styles){
        tagName.style[key] = styles[key];
    }
    return tagName;
};

查找元素的子元素,元素的文本元素,元素的兄弟元素

window.dom.find = function(seletor,scape){
    if(scape instanceof HTMLElement){
        return scape.querySelectorAll(seletor)
    }else{
        return document.querySelectorAll(seletor)
    }
};
window.dom.children = function(tagName){
    return tagName.children;
};
window.dom.text = function(tagName){
    var result = '';
    for(var i = 0;i < tagName.childNodes.length;i++){
        if(tagName.childNodes[i].nodeType === 3){
            result += tagName.childNodes[i].textContent.trim();
        }
    }
    return result;
};
window.dom.bigBorther = function(tagName){
    var previous = tagName.previousSibling;
    while(previous !== null && previous.nodeType !== 1){
        previous = previous.previousSibling;
    }
    return previous;
};
window.dom.nextBorther = function(tagName){
  var next = tagName.nextSibling;
  while(next !== null && next.nodeType !== 1){
    next = next.nextSibling;
  }
  return next;
}

代码实例

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 要进行DOM的增删改查的操作,首先要先搞懂: 什么是dom? Document Object Model,即文档对...
    饥人谷_Dylan阅读 1,871评论 0 50
  • 节点的增删改查 HTML的每个成分都可以看作是节点(文档节点、元素节点、文本节点、属性节点、注释节点,其中,属性节...
    柳叁叁阅读 359评论 0 0
  • 什么是DOM 文档对象模型 (DOM) 是 HTML 和 XML 文档的编程接口。它给文档(结构树)提供了一个结构...
    莱昂纳德刚阅读 155评论 0 0
  • DOM增删改查基本操作 基本概念 DOM是JavaScript操作网页的接口,全称为“文档对象模型”(Docume...
    _刘小c阅读 642评论 0 1
  • 时钟初始化 首先需要选择时钟源的来源,jz2440选择的是00,使用晶振的模式 时钟相关的寄存器设置 3.注意事项...
    sgy1993阅读 604评论 0 0