文檔對象模型(Document Object Model,DOM)是一種用于HTML和XML文檔的編程接口。它給文檔提供了一種結構化的表示方法,可以改變文檔的內容和呈現方式。我們最為關心的是,DOM把網頁和腳本以及其他的編程語言聯系了起來。DOM屬于瀏覽器,而不是JavaScript語言規范里的規定的核心內容。
?一 查找元素
1.1直接查找
1 document.getElementById 根據ID獲取一個標簽
2 document.getElementsByName 根據name屬性獲取標簽集合
3 document.getElementsByClassName 根據class屬性獲取標簽集合
4 document.getElementsByTagName 根據標簽名獲取標簽集合
1.2間接查找
1 parentNode // 父節點
2 childNodes // 所有子節點
3 firstChild // 第一個子節點
4 lastChild // 最后一個子節點
5 nextSibling // 下一個兄弟節點
6 previousSibling // 上一個兄弟節點
7
8 parentElement // 父節點標簽元素
9 children // 所有子標簽
10 firstElementChild // 第一個子標簽元素
11 lastElementChild // 最后一個子標簽元素
12 nextElementtSibling // 下一個兄弟標簽元素
13 previousElementSibling // 上一個兄弟標簽元素
?
二、操作
2.1內容
1 innerText 僅僅文本 自動過濾內部標簽
2 outerText
3 innerHTML HTML內容:包含文本和內本的淺表
4 innerHTML
5 value 值 input標簽 文本框中的內容
select 選中的值 還有一個特有的selectindex
textarea
?


<input id="i1" type="text" onfocus="fecus()" onblur="blu()" value="請輸入關鍵字"><div>onfocus 也適用于tab鍵</div><div style="color: red"><input type="text" placeholder="請輸入關鍵字">這種做法在目前只適合最新版本的瀏覽器,so目前推薦上面js的做法</div><script>function fecus(){var tag = document.getElementById('i1');var val = tag.value;if(val=="請輸入關鍵字"){tag.value='';}}function blu() {var tag = document.getElementById('i1');var val = tag.value;if(val.length==0){tag.value='請輸入關鍵字';}}</script>
?2.2 樣式操作
增加與刪除樣式
obj.className
obj.classList
classList.add()
classList.remove()
設置樣式的屬性
obj.style.color='red';
obj.style.fontSize='16px';
2.3 屬性操作
獲取屬性
obj.attributes
NamedNodeMap {0: id, 1: type, 2: onfocus, 3: onblur, 4: value, 5: class, 6: style, length: 7}
添加屬性
obj.setAttribute('id','id1')
刪除屬性
obj.removeAttribute('id')
2.4? 創建標簽 并添加到指定位置
創建標簽有兩種方法:1.通過字符串的方法? 2.通過dom來穿件
ps:jqure中并不具有創建標簽的辦法,so這里需要掌握!


<script>function addEle1() {var tag = '<p><input type="text" </p>';document.getElementById('i3').insertAdjacentHTML("beforeEnd",tag);}function addEle2() {var tag=document.createElement('input');tag.setAttribute('type','text')tag.style.color='red';tag.style.border='black 1px solid'var p=document.createElement('p');p.appendChild(tag);document.getElementById('i3').appendChild(p)}</script>
?2.5 實現表單的提交
在html中 需要使用 form中的 <input type='submit'> 來實現
在dom中,任何標簽都可以顯示表單的提交
?
2.6 其他操作
1 alert 彈出消息 2 console.log 在瀏覽器調試模式下輸出 3 confirm('真的要刪除嗎') 彈框確定 4 //url操作 5 location.href 獲取當前網址 6 location.href=' ' 重定向 7 location.reload() 頁面刷新 8 9 //定時器 10 setInterval(‘fuction’,5000) 一直在執行 11 clearIterval( obj) 清除setInterval對象 12 setTimeout(‘fuction’,5000) 只執行一次,5s之后再執行 13 qq郵箱刪除郵件,就使用了該技術 14 clearTimeout(obj) 與上個一樣


<div id="i1"></div><input type="button" onclick="settime()" value="刪除"><script>function settime(){document.getElementById('i1').innerText='已刪除';setTimeout(function () {document.getElementById('i1').innerText='';},5000)}</script>