原生js的dom操作
生活随笔
收集整理的這篇文章主要介紹了
原生js的dom操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
dom操作
獲取dom
標簽名獲取
doucment.getElementsByTagName("div")document.querySelector("div")className獲取
document.getElementsByClassName("class") // 偽數組,注意后面不需要家點了,其實前面已經很明確了document.querySelectorAll(".class") // 偽數組document.querySelector(".class") // 第一個符合要求的dom元素前兩個獲取的是所有含有"class"這個類名的dom,返回一個類數組
最后一個是獲取第一個含有"class"類名的dom
id獲取
document.getElementById("myId") document.querySelector("#myId")操作類名
類名的增刪改查
dom.classList // 獲取類名,返回數組 dom.classList.add("newName") // 添加類名 dom.classList.remove("newName") // 刪除類名返回類名的數組 dom.classList[0]可獲取第一個類名
用它來添加類名不會覆蓋原來的
dom.className dom.className="newName"獲取或設置className屬性,獲取的話,返回的是以空格分割的字符串,沒有classList方便
如果直接用className=“newName”,會覆蓋它原有的類名,只剩下新類名
操作style
dom.style.屬性名="屬性值" // 添加或修改樣式,不會影響原有的其他樣式 dom.style.removeProperty("屬性名") // 刪除style中某個屬性,不會影響其他樣式的生效操作屬性
dom.setAttribute("屬性名","屬性值") dom.getAttribute("屬性名") dom.hasAttribute("屬性名") dom.removeAttribute("屬性名")操作內容
dom.innerHTML // 獲取內容 dom.innerHTML="新的內容" // 修改內容創建添加、刪除dom
const child=document.createElement("span") // 創建domconst box=document.querySlector(".box") box.appendChild(child) // 添加dom; 放在最后,當box的最后一個親兒子document.querySelector('span').remove // 刪除dom總結
以上是生活随笔為你收集整理的原生js的dom操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HDU 4857 拓扑排序 优先队列
- 下一篇: HttpURLConnection, A