插入方法
这里是更多的元素插入方法,指明了不同的插入位置:
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)
—— 将node
替换为给定的节点或字符串。
下面是使用这些方法将列表项添加到列表中,以及将文本添加到列表前面和后面的示例:
<ol id="ol">
<li>0</li>
<li>1</li>
<li>2</li>
</ol>
<script>
ol.before('before'); // 将字符串 "before" 插入到 <ol> 前面
ol.after('after'); // 将字符串 "after" 插入到 <ol> 后面
let liFirst = document.createElement('li');
liFirst.innerHTML = 'prepend';
ol.prepend(liFirst); // 将 liFirst 插入到 <ol> 的最开始
let liLast = document.createElement('li');
liLast.innerHTML = 'append';
ol.append(liLast); // 将 liLast 插入到 <ol> 的最末尾
</script>
before
- prepend
- 0
- 1
- 2
- append
after
因此,最终列表将为:
before
<ol id="ol">
<li>prepend</li>
<li>0</li>
<li>1</li>
<li>2</li>
<li>append</li>
</ol>
after
insertAdjacentHTML/Text/Element
为此,我们可以使用另一个非常通用的方法:elem.insertAdjacentHTML(where, html)
。
该方法的第一个参数是代码字(code word),指定相对于 elem
的插入位置。必须为以下之一:
"beforebegin"
— 将html
插入到elem
前插入,"afterbegin"
— 将html
插入到elem
开头,"beforeend"
— 将html
插入到elem
末尾,"afterend"
— 将html
插入到elem
后。
第二个参数是 HTML 字符串,该字符串会被“作为 HTML” 插入。
例如:
<div id="div"></div>
<script>
div.insertAdjacentHTML('beforebegin', '<p>Hello</p>');
div.insertAdjacentHTML('afterend', '<p>Bye</p>');
</script>
……将导致:
<p>Hello</p>
<div id="div"></div>
<p>Bye</p>

这个方法有两个兄弟:
elem.insertAdjacentText(where, text)
— 语法一样,但是将text
字符串“作为文本”插入而不是作为 HTML,elem.insertAdjacentElement(where, elem)
— 语法一样,但是插入的是一个元素。
节点移除
想要移除一个节点,可以使用 node.remove()
。
请注意:如果我们要将一个元素 移动 到另一个地方,则无需将其从原来的位置中删除。
所有插入方法都会自动从旧位置删除该节点。
例如,让我们进行元素交换:
<div id="first">First</div>
<div id="second">Second</div>
<script>
// 无需调用 remove
second.after(first); // 获取 #second,并在其后面插入 #first
</script>
克隆节点:cloneNode
我们可以创建一个函数,并将代码放在其中。但是另一种方法是 克隆 现有的 div
,并修改其中的文本(如果需要)。
调用 elem.cloneNode(true)
来创建元素的一个“深”克隆 — 具有所有特性(attribute)和子元素。
如果我们调用 elem.cloneNode(false)
,那克隆就不包括子元素。
总结
-
创建新节点的方法:
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)
— 替换node
。node.remove()
— 移除node
。
文本字符串被“作为文本”插入。
-
这里还有“旧式”的方法:
parent.appendChild(node)
parent.insertBefore(node, nextSibling)
parent.removeChild(node)
parent.replaceChild(newElem, node)
这些方法都返回
node
。 -
在
html
中给定一些 HTML,elem.insertAdjacentHTML(where, html)
会根据where
的值来插入它:"beforebegin"
— 将html
插入到elem
前面,"afterbegin"
— 将html
插入到elem
的开头,"beforeend"
— 将html
插入到elem
的末尾,"afterend"
— 将html
插入到elem
后面。
另外,还有类似的方法,elem.insertAdjacentText
和 elem.insertAdjacentElement
,它们会插入文本字符串和元素,但很少使用。
-
要在页面加载完成之前将 HTML 附加到页面:
document.write(html)
页面加载完成后,这样的调用将会擦除文档。多见于旧脚本。