Windows對象主要是操作瀏覽器外層的東西,而DOM對象是操作瀏覽器里面的東西。
如果我們要操作網頁內容,那么一定需要操作標簽!
Document:文檔對象模型→DOM:可以做一些特效(搶票的)。摘出網頁的某一元素(標簽),找到他們然后增刪改。
一、找元素
1、根據ID找元素
document的獲取方式:
根據id進行獲取元素的方式如下:
var idq = document.getElementById("idq"); alert(idq);
2、根據class獲取元素
var o_class1 = document.getElementsByClassName("divclass");//(數組) alert(o_class1);
3、根據標簽獲取元素
4、根據name找元素
var ss = document.getElementsByName("ys") alert(ss[0]);
name是多個也是復數。
二、操作元素
1、操作內容
①非表單元素
(1)獲取文本:innerText
(2)設置文本
(3)獲取html代碼
如果想要獲取div中,包括span中的所有的代碼:
(4)設置Html代碼
設置HTML代碼,是可以增加動態效果的,輸出時頁面顯示效果。反之,如果使用innerText,就會將效果(<b>加粗</b>)同時也顯示出來了。
②表單元素
(1)賦值(設置一個值)
var b1 = document.getElementById("b1"); // alert(value = "請輸入內容"); //提示框輸出 b1.value = "請輸入內容"; //網頁輸出
(2)獲取值(取值)
alert(b.value);
2、操作屬性
①添加屬性(設置)
//添加屬性 var d1 = document.getElementById("idq"); d1.setAttribute("style","color: red");
②獲取屬性
getAttribute
<div id="idq" iid="我在這里"><span>獲取文本</span></div>
<script type="text/javascript"> var d1 = document.getElementById("idq"); alert(d1.getAttribute("iid")); </script>
③移除屬性
removeAttribute
var d1 = document.getElementById("idq"); d1.removeAttribute("iid");
3、操作樣式
①獲取樣式(只能獲取內聯樣式)
JS在獲取樣式時,只能獲取內聯的!其他像內嵌和外部的需要使用jquery才可以。
function showa(){ //1、獲取樣式 var d2 = document.getElementById("d2"); alert(d2.style.color) }
②設置樣式
function ang(){ var d2 = document.getElementById("d2"); //設置樣式 d2.style.backgroundColor = "red" }