dom節點的增刪改查
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>dom-test</title> <style> .setColor{ color: blue; } .setFtSz{ font-size: 16px; } </style> </head> <body> <div id="con"> <p id="tlt">html dom操作 增 刪 改 查</p> <p id="show">內容展示</p> <p id="showtest">測驗用例</p> </div> <script type="text/javascript"> let getDomById = document.getElementById('tlt') let getShowP = document.getElementById('show') let getDoms = document.getElementsByTagName('p') let getTestDom = document.getElementById('showtest') let pDom =getDomById.parentNode console.log(pDom) // 增 // 1、創建元素 2、填充內容3、追加到已有元素中或body中 let addNew = document.createElement('p') addNew.innerHTML = '我是新增的元素p' con.appendChild(addNew) let addNew2 = document.createElement('div') addNew2.innerHTML = '我是直接追加在body中的' document.body.appendChild(addNew2) // 刪 // 1、找需要洗掉的節點 2、需要洗掉節點父級 3、remove pDom.removeChild(getDomById) // 改 // 1、修改元素內容 getShowP.innerHTML = '我把原來內容改了' // 2、修改元素樣式 getShowP.style.color = '#f00' // 3、插入內容(insertBefore())/替換replaceChild() let addChildNew = document.createTextNode('子節點增加了內容') getShowP.appendChild(addChildNew) let reNew = document.createTextNode('我是來替換的') pDom.replaceChild(reNew, getShowP) //4、添加屬性 let addAtr = document.createAttribute('class') addAtr.value = 'setColor' getTestDom.setAttributeNode(addAtr) console.log(getTestDom.getAttribute('class')) // setColor getTestDom.setAttribute('class', 'setFtSz') // 更改屬性值 指定的屬性已存在,則僅設定/更改值, // 查 dom操作事件 // getElementById // getElementsByTagName // getElementsByClassName </script> </body> </html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/25039.html
標籤:JavaScript
上一篇:JavaScript基礎-03
