dom的操作方法
dom的獲取
- document.getElementById(‘id’)
- document.getElementsByClassName(‘class’)
- document.getElementsByTagName(‘tag’)
- document.getElementsByName(‘name屬性’)
- document.querySelect(‘選擇器’)
- document.querySelectAll(‘選擇器’)
節(jié)點(diǎn)類型nodeType
標(biāo)簽:1 ,屬性:2,文本:3
獲取相鄰的,或父子級(jí)的dom
- 下一個(gè)元素 :nextSibling,nextElementSibling(不包含文本節(jié)點(diǎn))
- 上一個(gè)元素:previousSibling,previousElementSibling(不包含文本節(jié)點(diǎn))
- 父元素:parentNode
- 子元素:childNodes,children(不包含文本節(jié)點(diǎn))
增刪改查
- 創(chuàng)建元素:document.createElement('tag')
- 添加dom元素:
在父元素的最后添加document.body.append('tag')
在父元素的中間插入document.body.insertBefore('要插入的標(biāo)簽','在誰之前') - 刪除元素:
在父元素中刪除子元素:parent.removeChild(tag)
直接刪除元素本身:item.remove() - 克隆元素:tag.cloneNode(Boolean) 默認(rèn)參數(shù)為false,不拷貝子節(jié)點(diǎn)
- 獲取自身屬性:dom.style.prop
- 設(shè)置自定義屬性:dom.setAttribute("prop","value")
- 獲取自定義屬性:dom.getAttribute("prop")
- 獲取頁(yè)面最終顯示樣式:getComputedStyle(tag).prop
冒泡與捕獲
- 冒泡:事件由內(nèi)向外傳播
- 捕獲:事件由外向內(nèi)傳播
解決冒泡 event.stopPropagation() IEwindow.event,cancelBubble=true
瀏覽器默認(rèn)事件
例:在form中按回車鍵就會(huì)提交表單;單擊鼠標(biāo)右鍵就會(huì)彈出context menu.
解決辦法event.preventDefault(); IEwindow.event.returnValue = false;retrun false;
dom注冊(cè)事件的幾種方法
1、標(biāo)簽上直接綁定
<button onclick="aaa()">按鈕<button>
2、獲取dom,調(diào)取事件
document.getElement(id).onclick=function(){}
3、addEventListener綁定事件
dom.addEventListener('click',function(){},Boolean) 默認(rèn)false(冒泡),true(捕獲)
總結(jié)