1.查找
DOM1:getElementById(),getElementsByTagName()
DOM擴展:querySelector()(返回第一個匹配的元素),querySelectorAll()(返回全部匹配的元素)
HTML5:getElementsByClassName()
2.插入
appendChild():末尾插入
insertBefore():特定位置插入
3.替換
replaceChild():接受兩個參數,第一個為要插入的節點,第二個為要替換的節點
4.刪除
removeChild()
實例代碼:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Dom節點操作</title> </head> <body> <ul id="list"><li>1</li><li>2</li><li>3</li></ul> <button id="add">插入</button> <button id="replace">替換</button> <button id="remove">刪除</button> <script > var list=document.getElementById('list'); var add=document.querySelector('#add'); var replace=document.querySelector('#replace'); var remove=document.querySelector('#remove'); var li=document.createElement('li'); li.innerHTML='hello'; function addNode(){ //尾插 //list.appendChild(li) //任意位置插 list.insertBefore(li,list.childNodes[2]) } function replaceNode(){ //替換任意位置,要替換第一個或者最后一個只需將第二個參數改為list.firstChild / lastChild list.replaceChild(li,list.childNodes[1]) } function removeNode(){ //移除首/尾元素 //list.removeChild(list.firstChild) // list.removeChild(list.lastChild) //移除任意位置上的元素 list.removeChild(list.childNodes[1]) } add.addEventListener('click',addNode); replace.addEventListener('click',replaceNode); remove.addEventListener('click',removeNode); </script> </body> </html>
運行視圖