當網頁被加載時,瀏覽器會建立頁面的文檔對象模型(Document Object Model)。javascript
HTML DOM 模型被構造爲對象的樹:css
經過可編程的對象模型,JavaScript 得到了足夠的能力來建立動態的 HTML。html
document.getElementById("id"); 經過id查找java
document.getElementsByTagName("tag"); 經過標籤名查找編程
document.getElementsByClassName("class"); 經過類名查找瀏覽器
----------實例---------dom
查找id="main"元素中的全部p元素post
var x = document.getElementById("main"); var y = x.getElementsByTagName("p");
document.getElementById("id").innerHTML = new content; //只能經過查找id修改ui
----------實例----------spa
<div class="alert01" id="yd"> <p id="yp" class="yp">HAHAHA</p> </div> var y = document.getElementById("yp"); y.innerHTML = "修改內容";
document.getElementById("id").attribute = 新屬性;
----------實例----------
<div> <img src="圖片ui/456.jpg" alt="" id="image"> </div> document.getElementById("image").src = "圖片ui/222.jpg"; document.getElementById("image").width = 300;
document.getElementById(id).style.property = 新樣式;
----------實例---------
在實例中樣式顯示的優先等級爲
width: 100px !important; > document.getElementById("image").width = 300; > document.getElementById("image").style.width = 500; > width:100px;
<style type="text/css"> #p1{ background: #000; color: #000 !important; /*優先*/ } #image{ width: 100px !important; /*優先*/ } </style> --------------------------------------------------------------- <div id="ex"> <img src="圖片ui/456.jpg" alt="" id="image"> <p id="p1" style="background:#666;">改變樣式</p> </div> ---------------------------------------------------------------- <script type="text/javascript"> document.getElementById("image").src = "圖片ui/222.jpg"; document.getElementById("image").width = 300; document.getElementById("image").style.width = 500; var p1 = document.getElementById("p1"); p1.style.background = "#99cccc"; p1.style.color = "#fff"; document.getElementById("ex").style.textAlign = "center"; </script>