JavaScript对HTML DOM文档树的常用操作
所有HTML元素都拥有的属性:id,title,lang,dir,className。
DOM集合:
- document.images 文档中所有图片集合
 - document.images[0] 等价document.images.item(0) 第一个图片
 - document.images.length 元素长度
 
类似集合还有form等。
JavaScript获取元素的方法:
- document.getElementById()
 - document.getElementByTagName()
 - document.getElementByName()
 
新支持的方法:
- document.querySelector() //类似CSS选择器法,返回第一个元素
 - document.querySelectorAll() //类似CSS选择器法,返回第一个元素
 
<!DOCTYPE html> <html> <head> <style type="test/css"> .box{ width:500px; height:500px; } </style> <script> function f1(){ var d1 = document.getElementById('d1'); var d2 = document.getElementByTagName('div'); var d3 = document.getElementByName('box'); } </script> </head> <body onload = "f1()" > <div id="d1" class="box"> <p>这只是一个例子</p> </div> </body> </html>
节点属性:
- nodeName
 - nodeValue
 - nodeType 值为1-12. 1是元素节点;2是属性;3是文本节点
 - parentNode
 - childNode
 - firstNode
 - lastNode
 - previousSibling 前一个兄弟节点
 - nextSibling 后一个兄弟节点
 - attributes 属性集合
 
<!DOCTYPE html> <html> <head> <script> function f1(){ var node = document.getElementById('d1'); alert(node.nodeName); } </script> </head> <body onload = "f1()" > <div id="d1"> <p>这只是一个例子</p> </div> </body> </html>
关于节点操作的方法:
- createElement() 创建元素节点
 - createTextNode() 常见文本节点
 - createAttribute()创建属性节点
 - appendChild() 追加子节点
 - insertBefore() 在指定子节点前插入新子节点
 - removeChild() 删除子节点
 - replaceChild() 替换子节点
 
<!DOCTYPE html> <html> <head> <script> function f1(){ //给div追加一个段落 var div = document.getElementById('d1'); var newP = document.craeteElement('p'); var textNode = document.createTextNode('This is an demo.'); newP.appendChild(textNode); div.appendChild(newP); } </script> </head> <body onload = "f1()" > <div id="d1"> <p>这只是一个例子</p> </div> </body> </html>
关于属性操作的方法:
- getAttribute(attrName) 获取属性对应的值
 - setAttribute(attrName,value)
 - removeAttribute(attrName)
 - hasAttribute(attrName) 是否有某属性
 
                    
                
                
            
        
浙公网安备 33010602011771号