js与DOM初步:访问html元素
2.常用DOM
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>js测试</title> </head> <script type="text/javascript"><!--通过标签id属性访问某一元素 --> function test1(){ var objElement = document.getElementById("button1"); alert("元素值为:"+objElement.value);}<!--通过标签访问一组元素(数组) --> function test2(){ var objElements = document.getElementsByTagName("input"); alert("第一个标签名为:"+objElements[0].tagName); alert("第二个元素值为:"+objElements[1].value); }<!--通过某个元素来访问其父元素 --> function test3(){ var objElement = document.getElementById("button3"); var obj = objElement.parentNode; alert("父元素的标签名:"+obj.tagName);}<!--通过某个元素来访问其同层第一个元素 --> function test4(){ var objElement = document.getElementById("button4"); var obj = objElement.parentNode.firstChild; alert("同层第一个元素:"+obj.value);}<!--标签修饰的内容当成文本 --> function test5(){ var objElements = document.getElementsByTagName("p"); objElements[0].innerText="CN:很高兴见到你!"; objElements[1].innerHTML='<a href="http://blog.csdn.net/nuptboyzhb/">NUPTboyZHB<a>';}<!--修改属性值 --> function test6(){ var objElement = document.getElementById("button6"); objElement.setAttribute("value","已修改");}<!--增加新的节点 --> function test7(){ var objFather = document.getElementById("button7").parentNode; var objImgNewElement = document.createElement("img"); objImgNewElement.setAttribute("src","http://avatar.csdn.net/C/2/1/1_nuptboyzhb.jpg"); objFather.appendChild(objImgNewElement);} </script> <body> <p>Nice to meet you!</p><p>Hello world!</p><div> <input id="button1" type="button" value="getElementById" onclick="test1()"> <input id="button2" type="button" value="getElementByTagName" onclick="test2()"> <input id="button3" type="button" value="Get-ParentNode" onclick="test3()"> <input id="button4" type="button" value="Get-firstChild" onclick="test4()"> <input id="button5" type="button" value="innerText-HTML" onclick="test5()"> <input id="button6" type="button" value="setAttribute" onclick="test6()"> <input id="button7" type="button" value="addElement" onclick="test7()"></div> </body></html>