javascript 如何在两个 DOM 节点之间插入 HTML 字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4023194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to insert HTML string in between two DOM nodes?
提问by actual
Consider following DOM fragment:
考虑以下 DOM 片段:
<div id="div-1">foo</div>
<div id="div-2">bar</div>
Is it possible to insert HTML string (EDIT: that contains tags to render) between divs withoutwrapping it in another div (EDIT: or some other tag) created via document.createElement and setting its innerHTML property?
是否可以在 div 之间插入 HTML 字符串(编辑:包含要呈现的标签)而不将其包装在通过 document.createElement 创建的另一个 div(编辑:或其他标签)中并设置其 innerHTML 属性?
回答by Andy E
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 rangesto insert the HTML. I've adapted it below to work for your scenario:
大多数浏览器都支持element#insertAdjacentHTML(),最终成为HTML5 规范中的标准。不幸的是,Firefox 7 及更低版本不支持它,但我设法找到了一种使用范围插入 HTML的解决方法。我已经在下面对其进行了调整以适合您的场景:
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);
}
Live example: http://jsfiddle.net/AndyE/jARTf/
回答by T.J. Crowder
This does it for straight text, which is how I read your original question (see below for an update for strings that include tags):
这适用于直接文本,这就是我阅读您原始问题的方式(有关包含标签的字符串的更新,请参见下文):
var div = document.getElementById('div-2');
var textNode = document.createTextNode('your text');
div.parentNode.insertBefore(textNode, div);
If you start with:
如果你开始:
<div id="div-1">foo</div>div id="div-2">bar</div>
(note that there's no whitespace between them) then the result of the above is exactly what you would get with this HTML:
(请注意,它们之间没有空格)那么上面的结果正是您使用此 HTML 获得的结果:
<div id="div-1">foo</div>your text<div id="div-2">bar</div>
If you really have that whitespace between the divs, you'll already have a text node there and the above will insert another one next to it. For virtually all intents and purposes, that doesn't matter, but if that bothers you, you can append to the existing text node instead if you like:
如果你真的有 div 之间的空白,你已经有一个文本节点,上面将在它旁边插入另一个。对于几乎所有的意图和目的,这并不重要,但如果这让您感到困扰,您可以根据需要附加到现有的文本节点:
var text = 'your text';
var div = document.getElementById('div-2');
var prev = div.previousSibling;
if (prev && prev.nodeType == 3) { // 3 == TEXT_NODE
// Prev is a text node, append to it
prev.nodeValue = prev.nodeValue + text;
}
else {
// Prev isn't a text node, insert one
var textNode = document.createTextNode(text);
div.parentNode.insertBefore(textNode, div);
}
Links to W3C docs: insertBefore, createTextNode
W3C 文档的链接:insertBefore,createTextNode
Including HTML tags
包括 HTML 标签
In your revised question you've said you want to include tags to be interpreted in doing all this. It's possible, but it's roundabout. First you put the HTML string into an element, then you move the stuff over, like this:
在您修改后的问题中,您曾说过要在执行所有这些操作时包含要解释的标签。这是可能的,但它是迂回的。首先将 HTML 字符串放入一个元素中,然后将内容移过去,如下所示:
var text, div, tempdiv, node, next, parent;
// The text
text = 'your text <em>with</em> <strong>tags</strong> in it';
// Get the element to insert in front of, and its parent
div = document.getElementById('div-2');
parent = div.parentNode;
// Create a temporary container and render the HTML to it
tempdiv = document.createElement('div');
tempdiv.innerHTML = text;
// Walk through the children of the container, moving them
// to the desired target. Note that we have to be sure to
// grab the node's next sibling *before* we move it, because
// these things are live and when we moev it, well, the next
// sibling will become div-2!
node = tempdiv.firstChild;
next = node.nextSibling;
while (node) {
parent.insertBefore(node, div);
node = next;
next = node ? node.nextSibling : undefined;
}
But here there be dragons, you have to select the container element as appropriate to the content you're inserting. For instance, we couldn't use a <tr>in your text with the code above because we're inserting it into a div, not a tbody, and so that's invalid and the results are implementation-specific. These sorts of complexities are why we have libraries to help us out. You've asked for a raw DOM answer and that's what the above is, but I really would check out jQuery, Closure, Prototype, YUI, or any of several others. They'll smooth a lot of stuff over for you.
但是这里有 Dragons,您必须根据要插入的内容选择容器元素。例如,我们不能<tr>在带有上述代码的文本中使用 a ,因为我们将它插入到 a 中div,而不是 a 中tbody,因此这是无效的,并且结果是特定于实现的。这些复杂的问题是我们有图书馆来帮助我们的原因。您要求提供原始 DOM 答案,这就是上述内容,但我真的会检查jQuery、Closure、Prototype、YUI或其他几个。他们会为你解决很多问题。
回答by angelcervera
Using jquery it is very simple:
使用 jquery 非常简单:
$("#div-1").after("Other tag here!!!");
See: jquery.after
请参阅:jquery.after
It is obvious that javascript is not a pure javascript solution.
很明显,javascript 不是纯 javascript 解决方案。
回答by Floyd
var neuB = document.createElement("b");
var neuBText = document.createTextNode("mit fettem Text ");
neuB.appendChild(neuBText);
document.getElementById("derText").insertBefore(neuB, document.getElementById("derKursiveText"));
You search for: insertBefore
您搜索的是:insertBefore

