拓展:文档碎片
document.createDocumentFragment()
例:
let docFrag = document.createDocumentFragment();
for(let i=0;i<data.length;i++){
let option = document.createElement("option");
option.value = data[i]["sheng"];
option.innerText = data[i]["sheng"];
docFrag.appendChild(option);
}
sheng.appendChild(docFrag);
循环创建的元素放入文档碎片中,最后将文档碎片添加入网页,,这样只用改变一次节点树,节约性能。
1、操作节点:
替换:
父节点.replaceChild(新节点,旧节点);
插入:
父节点.insertBefore(新节点,引用节点);
追加:
父节点.appendChild(子节点);
删除:
父节点.removeChild(子节点);
克隆:
父节点.cloneNode(deep);
deep为true时克隆节点及后代的所有内容,为false(默认)时只克隆节点本身.
2、js对类名操作
设置类名:
element.className = "类名"
element.setAttribute("class","类名")
追加类名:
element.classList.add("类名");
移除类名:
element.className = ""; //删除所有
element.classList.remove("类名"); //移除单个
3、获取属性节点
元素节点.attributes //获取当前元素所有的属性节点
元素节点.getAttributeNode("属性名");//获取某个属性节点
元素节点.getAttribute("属性名");//获取对应属性的值
对属性操作:
元素节点.getAttribute("属性名");//获取对应属性的值
元素节点.setAttribute("属性名","值");//设置对应属性的值
元素节点.removeAttribute("属性名");//删除对应的属性
4、操作css样式
语法:
元素节点.style.样式名
获取style属性(行内),设置style属性(行内样式)
注:样式名如果是两个单词连接,用小驼峰命名
例:
e.style.backgroundColor = "";
获取最终样式
DOM浏览器(谷歌,火狐, ie edge)
getComputedStyle(元素节点, null).样式名
非DOM浏览器(IE)
元素节点.currentStyle().样式名