Skip to contentDom 节点操作总结
创建新节点的方法:
document.createElement(tag) —— 用给定的标签创建一个元素节点document.createTextNode(value) —— 创建一个文本节点(很少使用)elem.cloneNode(deep) —— 克隆元素,如果 deep==true 则与其后代一起克隆
插入和移除节点的方法(文本字符串被“作为文本”插入):
node.append(...nodes or strings) —— 在 node 末尾插入node.prepend(...nodes or strings) —— 在 node 开头插入node.before(...nodes or strings) —— 在 node 之前插入node.after(...nodes or strings) —— 在 node 之后插入node.replaceWith(...nodes or strings) —— 替换 nodenode.remove() —— 移除 node
“旧式”的方法(这些方法都返回 node):
parent.appendChild(node)parent.insertBefore(node, nextSibling)parent.removeChild(node)parent.replaceChild(newElem, node)
elem.insertAdjacentHTML/Text/Element(where, html) 会根据 where 的值来插入:
"beforebegin" —— 将 html 插入到 elem 前面"afterbegin" —— 将 html 插入到 elem 的开头"beforeend" —— 将 html 插入到 elem 的末尾"afterend" —— 将 html 插入到 elem 后面