dom指的是document。整個doc下還有head,body,而head,body下面又有link p a等css
//1.xxxx將會覆蓋Hello <body> <p>Hello</p> <button onclick="demo()">按鈕</button> <script> function demo(){ document.write("xxxx"); } </script> </body> //2.尋找元素和改內容 <body> <p id="pid">Hello</p> <button onclick="demo()">按鈕</button> <script> function demo(){ document.getElementById("pid").innerHTML = @"hah"; } </script> </body> //3.更改html屬性 <body> <a id="aid" href="http://www.baidu.com">baidu</a> <button onclick="demo()">按鈕</button> <script> function demo(){ document.getElementById("aid").href = "http://www.hao123.com"; } </script> </body>
與操做HTML相似。在script更快css樣式
html
<body> <button id="btn">按鈕</button> <script> //句柄操做 var x = document.getElementById("btn"); x.addEventListener("click",hello); x.addEventListener("click",world); function hello(){ alert("hello"); } function world(){ alert("world"); } </script> </body>
<body> <p name="pn">Hello</p> <p name="pn">Hello</p> <p name="pn">Hello</p> <p name="pn">Hello</p> <a id="aid" title="獲得了a標籤屬性">AAA</a> <a id="aid2">BBB</a> <ul> <li id="l">1</li> <li>2</li> <li>3</li> </ul> <div id="div" style="background-color: aqua"> <p id="pid">xxxxxx</p> </div> <script> //獲取name function getName(){ var count = document.getElementsByName("pn") var p = count[2]; p.innerHTML = "world" } getName(); //獲取元素屬性 function getArr(){ var anode = document.getElementById("aid").getAttribute("id"); alert(anode) } //getArr(); //設置元素屬性 function setAttr(){ var andoe = document.getElementById("aid2"); andoe.setAttribute("title","動態設置attr"); alert(andoe.getAttribute("title")); } //setAttr(); //訪問子節點 function getChildNode(){ var childNode = document.getElementsByTagName("ul")[0].childNodes; alert(childNode.length); } //getChildNode(); //訪問父節點 function getParentNode(){ var div = document.getElementById("l"); alert(div.parentNode.nodeName); } //getParentNode(); //建立節點 function createNode(){ var body = document.body; var input = document.createElement("input"); input.type = "button"; input.value = "按鈕" body.appendChild(input) } //createNode(); //插入節點 function insetNode(){ var div = document.getElementById("div"); var oldP = document.getElementById("pid"); var newnode = document.createElement("p"); newnode.innerHTML = "insert"; div.insertBefore(newnode,oldP); } insetNode(); //刪除節點 function removeNode(){ var div = document.getElementById("div"); div.removeChild(div.childNodes[1]);//1開始算起 不是0 } removeNode(); //獲取頁面size function getSize(){ var height = document.documentElement.offsetHeight; var width = document.documentElement.offsetWidth; alert(height+","+width); } getSize(); </script> </body>