步骤:
1、获取元素
2、注册事件 处理程序
1. Change the element content (readable)
(1) el.innerHTML : recognize html tags, keep spaces and newlines, recommended
(2) el.innerText : Does not recognize html tags, will remove spaces and newlines, non-standard
read or set element text
** el.textContent
2. Node operation (create node, insert, delete, replace)
Create an element node: createElement (tag name)
Create a text node: createTextNode(text)
let p=document.createElement('p');
let p=document.createTextNode('酱油');
Add child node to parent element
parent.appendChild(new node); Add after the last child element
parent.insertBefore(new node, child node); Insert a new node before a child node
Delete child node from parent element
parent.removeChild (removed child element), the parent element calls this method
Methods of the Node object
(1) Get the node of the element to be deleted
(2) Get the parent node of the element to be deleted
(3) Delete the node to be deleted from the parent node
example:
document.body.removeChild(p);
p.parentNode.NodeChild(p);//父元素调用该方法
Replace child nodes of parent element
parent.replaceChild(newNode,oldNode)
Methods of the Node object
(1) Get the element node to be replaced
(2) Get the parent element node of the element to be replaced
(3) Replace the atomic node with a new child node
newNode=document.createElement('h2');
newNode.textContent='番茄';
document.body.replaceChild(newNode,p);
Operates on the child nodes of the parent element
ele.prepend(node list): Insert a node or text before the first node of the node
ele.append(node list) : insert a node or text after the last node of the node
operate on the element itself
ele.before(node list): Insert nodes before element nodes
ele.after(node list): Insert a node after the element node
el.remove(): delete element node
el.replaceWith(node list): Replace the element node with the parameter node
Parses text into elements for insertion into the tree
Format: insertAdjacentHTML(position,text)
beforebegin: before the element itself
afterbegin: before the first child element of the element
beforeend: after the first child element of the element
afterend: behind the element itself