Summary of js methods of manipulating DOM

DOM:
DOM (Document Object Model) document object model. DOM provides a structured representation method for HTML, and defines the method specifications for accessing and processing document structures.
HTML can be understood as a collection of DOM nodes, mainly composed of element nodes, text nodes, and attribute nodes.
The method of js operation DOM:
js operation dom is mainly divided into adding, deleting and modifying element nodes, text nodes and attribute nodes:
judging the type of element nodes
and adding new nodes:

var newNode=document.createElement("div");  //创建一个元素节点
var textNode=document.createTextNode("hello world!");  //创建一个文本节点
var cloneNode =newNode.cloneNode(true);//克隆一个节点,参数true表示会克隆当前节点以及他的所有子节点,flase表示只克隆当前节点,默认为false
document.createDocumentFragment();//创建文档对象变量,主要用来临时存储节点,大量操纵dom时性能会有很大的提升

delete node

​
​
var deleteNode = parentNode.removeChild(item);//删除指定的子节点,并返回   deleteNode只是在dom树中删除了,但在内存中还可以访问

​

​

modify node

node.appendChild(newNode);// 在指定元素后面新增子节点
parentNode.insertBefore(newNode,node);  //在parentNode的子节点newNode前面插入newNode节点
parentNode.replaceChild(newNode,oldNode);//用oldNode节点替换parentNode的子节点newNode

find node

var parentNode=document.getElementById("list");//返回第一个带有指定id的元素
var classList=document.getElementsByClassName("wrapper"); //返回所有带有指定class的元素的集合(返回数组形式)
var tagList=document.getElementsByTagName("li");//返回所有带有指定标签的元素的集合(返回数组形式)   // *表示查找所有标签
var list=document.querySelector(".wrapper");//返回第一个带有指定id或class的元素
var allList=document.querySelectorAll(".wrapper");//返回所有带有指定id或class的元素

Find element nodes through the relationship between nodes, the relationship diagram between dom nodes and the operation method are as follows


var node =document.getElementById("list");
// classList方法操作元素的class属性
node.classList.add("test"); //给node节点添加一个class
node.classList.remove("test");//删除node节点名为test的class
node.classList.replace("old-class","new-class");//替换node节点的class
var hasClass = node.classList.contains("test");//node节点是否存在给定的class,如果存在则返回 true,否则返回 false。
node.classList.toggle("test")//如果节点已经存在给定的class则删除,如果没有则添加
 
node.setAttribute("id","123");//给node节点设置id=123
var id = node.getAttribute("id");//获取node节点的id属性值
var hasAttr =node.hasAttribute("id");//判断node节点是否存在id属性
 
// dataset方法获取元素的data- 属性值
var dataId=node.dataset.id; //获取node节点的data-id属性值
var dataName=node.dataset.userName;//类似data-user-name属性必须使用驼峰式来访问
'id' in node.dataset     // 判断node节点是否有data-id属性
 
// style方法修改元素的样式
node.style.color = 'red';   //设置color样式
node.style.setProperty('font-size', '16px');  //设置font-size样式
node.style.removeProperty('color');  //移除color属性

get element type


element.nodeType 
//返回元素的节点类型 
1元素节点
2属性节点 
3文本节点 
4CDATA节点 
5实体引用名称节点 
6实体名称节点
7处理指令节点  
8注释节点  
9文档节点  
10文档类型节点 
11文档片段节点 
12DTD声明节

Get the text value of the current node


element.innerHtml  //返回当前节点的所有文本包含html
element.innerText //返回当前节点及所有后代节点的文本值,不包含html

Guess you like

Origin blog.csdn.net/Ass12454548/article/details/128751632