创建dom元素
var oLi = document.creteElement('li'); //创建li
var aLi = oUl.getElementsByTagName('li');
oLi.innerHTML = oTxt.value
oUl.appendChild(oLi)
父节点.insertBefore(子节点,谁之前)
oUl.insertBefore(oLi,aLi[0]) 如果一个都没有就会出错
if(aLi.length==0)
{
oUl.appendChild(oLi)
}else{
oUl.insertBefore(oLi,aLi[0])
}
window.onload = function()
{
var oUl = document.getElementById("ul1");
var aLi = oUl.getElementsByTagName('li');
var oBtn = document.getElementById('btn1');
var oTxt = document.getElementById('txt');
oBtn.onclick = function()
{
var oLi = document.createElement('li');
oLi.innerHTML = oTxt.value;
if(aLi.length>0)
{
oUl.insertBefore(oLi,aLi[0]);
}else{
oUl.appendChild(oLi);
}
}
}
删除 removeChild(子节点)
oUl.remove(this.parentNode)
<script>
window.onload = function()
{
var oUl = document.getElementById("ul1");
var aLi = oUl.getElementsByTagName('li');
var oA = oUl.getElementsByTagName('a');
for(var i=0;i<oA.length;i++)
{
oA[i].onclick = function(){
oUl.removeChild(this.parentNode)
}
}
}
</script>
文档碎片,提高文档效率的(理论上)
new Date().getTime();
时间戳
createDocumentFragment
实际上还不如之前的那种
dom1 dom2
火狐是最标准
dom的childNodes 是会包含txt文本节点
nodeType 节点类型 配合使用
3 文本节点
1 元素节点 标签节点
<script>
window.onload = function(){
var oUl = document.getElementById('ul1');
for(var i=0;i<oUl.childNodes.length;i++)
{
if(oUl.childNodes[i].nodeType == 1)
{
oUl.childNodes[i].style.background = "red"
}
}
}
</script>
children 兼容版本的childNodes
<script>
window.onload = function(){
var oUl = document.getElementById('ul1');
for(var i=0;i<oUl.children.length;i++)
{
oUl.children[i].style.background = "red"
}
}
</script>
父节点
parentNode
<script>
window.onload = function(){
var oA = document.getElementsByTagName('a');
for(var i=0;i<oA.length;i++)
{
oA[i].onclick = function(){
this.parentNode.style.display="none";
}
}
}
</script>
offsetParent 定位的父集
firstChild 火狐下用
firstElementChild
lastChild
var oFirst = oUl.firstElementChild || oUl.firstChild
兄弟节点
nextSibling nextElementSibling
prviousSibling
操作元素属性:
通过id操作 document.getElementById
dom方式操作
otxt.setAttribute('value',"22");
getAttribute('id')
removeAttribute
用className 选择元素
document.getElementsByClassName
var getElementsByClass = function(searchClass,node,tag) {
var classElements = new Array();
if ( node == null )
node = document;
if ( tag == null )
tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;