使用本机 javaScript 附加 html
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42517697/
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
Appending html using native javaScript
提问by Meek
I need to append some html to an existing element using pure javaScript:
我需要使用纯 javaScript 将一些 html 附加到现有元素:
function create(htmlStr) {
var frag = document.createDocumentFragment(),
temp = document.createElement('div');
temp.innerHTML = htmlStr;
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
return frag;
}
var target = document.querySelectorAll(".container-right");
var fragment = create(
'<div class="freetext"><p>Some text that should be appended...</p></div>'
);
document.body.insertBefore(fragment, document.body.childNodes[0]);
It's kind of working, but I have two questions:
它有点工作,但我有两个问题:
How can I make sure that the html fragment is appended to the div with the class
container-rightand not just the body? Changing the last line todocument.body.insertBefore(fragment, target);doesn't work.How can I insert the html afterthe content in the target element - after the existing content - like jQuery's append()?
如何确保将 html 片段与类一起附加到 div
container-right而不仅仅是正文?将最后一行更改为document.body.insertBefore(fragment, target);不起作用。如何在目标元素中的内容之后插入 html - 在现有内容之后 - 就像 jQuery 的 append()?
Any help is much appreciated.
任何帮助深表感谢。
回答by Tim Consolazio
Well, I know this works:
好吧,我知道这有效:
let elem = document.querySelector ( 'css-selector (id or class)' )
That should give you your element. Then you do this:
那应该给你你的元素。然后你这样做:
elem.innerHTML = elem.innerHTML + myNewStuff;
That'll append your html to the innerHTML of the element. I tried it quickly, it works.
这会将您的 html 附加到元素的 innerHTML 中。我很快就试过了,它有效。
回答by Paulo Pereira
var target = document.querySelector(".container-right");
var p = document.createElement('p');
p.innerHTML = "Some text that should be appended...";
var div = document.createElement('div');
div.appendChild(p);
var fragment = document.createDocumentFragment();
fragment.appendChild(div);
target.appendChild(fragment);
回答by Justin Taddei
Try this:
尝试这个:
var target = document.querySelector(".container-right");
target.innerHTML += '<div class="freetext"><p>Some text that should be appended...</p></div>';

