如何在两个DOM节点之间插入HTML字符串? [英] How to insert HTML string in between two DOM nodes?

查看:164
本文介绍了如何在两个DOM节点之间插入HTML字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下DOM片段:

<div id="div-1">foo</div>
<div id="div-2">bar</div>

是否可以在div之间插入HTML字符串(编辑:包含要呈现的标签)没有将其包装在另一个通过document.createElement创建的div(编辑或其他标签)中,并设置其innerHTML属性?

Is it possible to insert HTML string ( that contains tags to render) between divs without wrapping it in another div ( or some other tag) created via document.createElement and setting its innerHTML property?

推荐答案

大多数浏览器支持 元素#insertAdjacentHTML( ) ,最终成为标准的在HTML5规范中。不幸的是,Firefox 7及更低版本不支持,但我设法找到使用范围的解决方法插入HTML。我已经调整了下面的方式为您的方案工作:

Most browsers support element#insertAdjacentHTML(), which finally became standard in the HTML5 specification. Unfortunately, Firefox 7 and lower don't support it, but I managed to find a workaround that uses ranges to insert the HTML. I've adapted it below to work for your scenario:

var el = document.getElementById("div-2"),
    html = "<span>Some HTML <b>here</b></span>";

// Internet Explorer, Opera, Chrome, Firefox 8+ and Safari
if (el.insertAdjacentHTML)
    el.insertAdjacentHTML ("beforebegin", html);
else {
    var range = document.createRange();
    var frag = range.createContextualFragment(html);
    el.parentNode.insertBefore(frag, el);
}

现场示例: http://jsfiddle.net/AndyE/jARTf/

这篇关于如何在两个DOM节点之间插入HTML字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆