- 庫
把建立一個對象,作為封裝JS函數方法的庫,綁定在最頂層元素window下
window.dom = {};
使用原始的函數方法進行添加帶屬性有文本內容的元素、元素還可以有一些列子元素
window.dom.create = function(tagName,children,attributes){
//獲取要添加的標簽,創建這個標簽
var tag = document.createElement(tagName);
//如果children的數據類型是字符串的情況下
if(typeof children === 'string'){
//則直接把字符串文本添加到標簽里
tag.textContent = children;
//如果children是元素的情況下
}else if(children instanceof HTMLElement){
//則把這個元素添加進之前的標簽里,作為之前新增標簽的子元素
tag.appendChild(children);
//如果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]); } }}
//attributes是否為對象
if(typeof attributes === 'object'){
//然后將屬性對象給新增標簽的樣式添加屬性
for(var key in attributes){ tag.style[key] = attributes[key]; } }return tag; };
封裝給元素添加屬性的方法
window.dom.attr = function(tag,attr){
for(var key in attr){
tag.setAttribute(key,attr[key]);
}
};
- 封裝給元素添加樣式的方法
window.dom.style = function(tag,attr){
for(var key in attr){
tag.style[key] = attr[key];
}
};
用來清空元素里的所有子節點
window.dom.emp = function(tag){
//得到第一個子節點
var firstChild = tag.childNodes[0];
//如果第一個子節點存在,則移除。
//然后重新計算節點位置,繼續刪除第一個子節點,直到子節點不存在位置
while(firstChild){ firstChild.remove(); firstChild = tag.childNodes[0]; } };
查找包含所有指定標簽的數組
window.dom.find = function(selector,scope){
var tag = (scope instanceof HTMLElement) ? scope : document;
return tag.querySelectorAll(selector);
};
- 查找元素的所有子元素
window.dom.children = function(tag){
return tag.children;
};
- 查找元素所有子節點的文本內容
window.dom.text = function(tag){
var text = '';
for(var i = 0;i < tag.childNodes.length;i++){
if(tag.childNodes[i].nodeType === 3){
text += tag.childNodes[i].textContent.trim();
}
}
return text;
};
- 查找元素的前一個元素
window.dom.bigBrother = function(tag){
var previous = tag.previousSibling || null;
while(previous !== null && previous.nodeType !== 1){
previous = previous.previousSibling;
}
return previous;
}