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