添加元素原来还有insertAdjacent这种方法。insertAdjacentHTML(sWhere,html),insertAdjacentText(sWhere,text),insertAdjacentElement(sWhere,element)
这是ie弄出来的 所以ie基本支持,
chrome(47.0.2526.106 m) 对三个方法都支持
测试ff(40.0.3)不支持 insertAdjacentElement方法
sWhere的取值有beforeBegin,beforeEnd,afterBegin,afterEnd
区别如下
<body> <div id="tag">tag</div> <script> var el = document.getElementById("tag");
el.insertAdjacentHTML("beforeBegin", "<div>beforeBegin html</div>") el.insertAdjacentHTML("beforeEnd", "<div>beforeEnd html</div>") el.insertAdjacentHTML("afterBegin", "<div>afterBegin html</div>") el.insertAdjacentHTML("afterEnd", "<div>afterEnd html</div>") el.insertAdjacentText("beforeBegin", "beforeBegin text") el.insertAdjacentText("beforeEnd", "beforeEnd text") el.insertAdjacentText("afterBegin", "afterBegin text") el.insertAdjacentText("afterEnd", "afterEnd text")
el.insertAdjacentElement(‘beforeBegin‘, document.createElement(‘div‘)) </script> </body>
运行后结果
<body> <div>beforeBegin html</div> beforeBegin text <div></div> <div id="tag"> afterBegin text <div>afterBegin html</div> tag <div>beforeEnd html</div> beforeEnd text </div> afterEnd text <div>afterEnd html</div> <script> var el = document.getElementById("tag"); el.insertAdjacentHTML("beforeBegin", "<div>beforeBegin html</div>") el.insertAdjacentHTML("beforeEnd", "<div>beforeEnd html</div>") el.insertAdjacentHTML("afterBegin", "<div>afterBegin html</div>") el.insertAdjacentHTML("afterEnd", "<div>afterEnd html</div>") el.insertAdjacentText("beforeBegin", "beforeBegin text") el.insertAdjacentText("beforeEnd", "beforeEnd text") el.insertAdjacentText("afterBegin", "afterBegin text") el.insertAdjacentText("afterEnd", "afterEnd text") el.insertAdjacentElement(‘beforeBegin‘, document.createElement(‘div‘)) </script>
时间: 2024-10-21 05:10:00