DOM 操作初学者指南
元素选择器
查询选择器
创建元素
改变属性
删除元素
DOM 或文档对象模型是网页或文档的表示,根据MDN ,可以使用 JavaScript 等脚本语言进行修改。
它将DOM HTML文档描述为一个分层的树形结构,文档树中的每个元素称为一个节点。
DOM 节点代表构成网页的所有组件。例如,head 标签被视为一个节点。大多数节点都有起始标签和结束标签。这些标签内可以嵌套内容。内部节点称为子节点,外部节点称为其父节点。
有些节点是自闭合标签,例如“img”标签。这些节点被称为空节点,它们不能作为父节点,也就是说,它们内部不能嵌套其他元素。
由于“document”是一个具有属性(properties)的对象,因此它也具有属性和方法。为了访问对象中的内容,我们使用选择器和查询方法来更改浏览器中显示的内容。
元素选择器
document.getElementById("idName")
//This method only returns the one element by the specified ID.
document.getElementByClass("className")
//This method returns all elements inside the whole document by the class you specified.
document.getElementById("someElement").getElementsByClassName("className")
//It works in all elements of the DOM, this will return all elements by the class you specify inside the element you want
查询选择器
document.querySelector("#idName")
//This method takes one argument, which is a CSS selector & returns the first element that matches the selector.
document.querySelectorAll(".className")
//Works similar to above; returns a node list collection of all matching elements.
创建元素
附加
document.createElement("body")
//this method creats the element, but it does not show up on the page.
document.body.append(element)
//this method gets the element to appear on the page.
.内部HTML
<h1 id="greetings"> HELLO </h1>
let element = document.querySelector("#greeting")
element.innerHTML = "Welcome"
//selects the h1 called greetings and changes HELLO to welcome
改变属性
const element = document.querySelector(".container")
element.style.backgroundColor="#f0f0f0"
//changes the selected elements(in this case the container class) color to grey
删除元素
element.remove()
//removes a whole element from the page
这只是对一些用于操作 DOM 的方法的基本概述。
文章来源:https://dev.to/iqramqra/a-beginners-guide-to-dom-manipulation-45bk