下面介绍几个新的插入DOM的API:html
insertAdjacentText insertAdjacentHTML insertAdjacentElement
以上三个方法分别是用来向一个DOM元素中插入文本,字符串格式的html代码结构,以及插入DOM元素;这三个方法的用法基本是一致的。spa
insertAdjacentText(position, string); insertAdjacentHTML(position, htmlstring); insertAdjacentElement(position, element);
其中,参数position表示的是插入的位置,字符串类型,取值能够有如下:code
beforebegin afterbegin beforeend afterend
能够用以下的结构来描述具体的位置:htm
<!-- beforebegin --> <p> <!-- afterbegin --> foo <!-- beforeend --> </p> <!-- afterend -->
接下来看一个demo:
有以下的DOM结构:图片
<div id="wrap"> <div id="content"> <p>origin test , test only</p> </div> </div> <script> window.onload = function () { var content = document.getElementById('content'); content.insertAdjacentText('beforebegin', 'test beforebegin'); content.insertAdjacentText('afterbegin', 'test afterbegin'); content.insertAdjacentText('beforeend', 'test beforeend'); content.insertAdjacentText('afterend', 'test afterend'); } </script>
执行以上代码后,DOM结构以下图所示:ip
insertAdjacentHTML 和 insertAdjacentElement 也是相似的。element