增
添加元素,子元素(子元素,文本),属性
1 | window.dom={}; |
2 | window.dom.create = function (tagName,children,attributes) { |
3 | var tag = document.createElement(tagName); |
4 | if(typeof children === 'string'){ |
5 | var text =document.createTextNode(children); |
6 | tag.appendChild(text); |
7 | }else if(children instanceof HTMLElement){ |
8 | tag.appendChild(children) |
9 | } else if(children instanceof Array){ |
10 | for(var i=0;i<children.length;i++){ |
11 | if(typeof children[i] === 'string'){ |
12 | tag.appendChild(document.createTextNode(children[i])) |
13 | }else if(children[i] instanceof HTMLElement){ |
14 | tag.appendChild(children[i]) |
15 | } |
16 | } |
17 | } |
18 | if (typeof attributes === 'object'){ |
19 | for(var key in attributes){ |
20 | tag.setAttribute(key,attributes[key]) |
21 | } |
22 | } |
23 | return tag; |
24 | }; |
删
删除元素的所有子元素
1 | window.dom.empty = function(tagName){ |
2 | var firstChild = tagName.childNodes[0]; |
3 | while(firstChild){ |
4 | firstChild.remove(); |
5 | firstChild = tagName.childNodes[0]; |
6 | } |
7 | }; |
改
改变元素的属性
1 | window.dom.attr = function(tagName,attributes){ |
2 | for(var key in attributes){ |
3 | tagName.setAttribute(key,attributes[key]); |
4 | } |
5 | return tagName; |
6 | }; |
7 | |
8 | window.dom.style = function(tagName,styles){ |
9 | for(key in styles){ |
10 | tagName.style[key] = styles[key]; |
11 | } |
12 | return tagName; |
13 | }; |
查
查找元素的子元素,元素的文本元素,元素的兄弟元素
1 | window.dom.find = function(seletor,scape){ |
2 | if(scape instanceof HTMLElement){ |
3 | return scape.querySelectorAll(seletor) |
4 | }else{ |
5 | return document.querySelectorAll(seletor) |
6 | } |
7 | }; |
8 | window.dom.children = function(tagName){ |
9 | return tagName.children; |
10 | }; |
11 | window.dom.text = function(tagName){ |
12 | var result = ''; |
13 | for(var i = 0;i < tagName.childNodes.length;i++){ |
14 | if(tagName.childNodes[i].nodeType === 3){ |
15 | result += tagName.childNodes[i].textContent.trim(); |
16 | } |
17 | } |
18 | return result; |
19 | }; |
20 | window.dom.bigBorther = function(tagName){ |
21 | var previous = tagName.previousSibling; |
22 | while(previous !== null && previous.nodeType !== 1){ |
23 | previous = previous.previousSibling; |
24 | } |
25 | return previous; |
26 | }; |
27 | window.dom.nextBorther = function(tagName){ |
28 | var next = tagName.nextSibling; |
29 | while(next !== null && next.nodeType !== 1){ |
30 | next = next.nextSibling; |
31 | } |
32 | return next; |
33 | } |