在不使用innerHTML的情况下在JavaScript中更改HTML [英] Changing HTML in JavaScript without innerHTML

查看:65
本文介绍了在不使用innerHTML的情况下在JavaScript中更改HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我的代码很简单:

Let's say my code was something pretty simple like this:

let content = "";

for(let i=0; i<array.length; i++){
    content+='<h1>array[i]</h1>';
}

document.getElementById('some_id').innerHTML = content;

我不喜欢将HTML放入JavaScript代码的想法,但是我不知道其他任何不使用JQuery的 html()方法,或简单地以编程方式创建新的DOM元素.

I don't like the idea of putting HTML in my JavaScript code, but I don't know any other way of inserting elements into the DOM without using innerHTML, JQuery's html() method, or simply creating new DOM elements programmatically.

在业界或为了最佳实践,从JavaScript插入HTML元素的最佳方法是什么?

In the industry or for best practices, what's the best way to insert HTML elements from JavaScript?

提前谢谢!

推荐答案

您可以使用 DOMParser 和ES6字符串文字:

You can use a DOMParser and ES6 string literals:

const template = text => (
`
<div class="myClass">
    <h1>${text}</h1>
</div>
`);

您可以在内存中创建一个片段:

You can create a in memory Fragment:

const fragment = document.createDocumentFragment();
const parser = new DOMParser();
const newNode = parser.parseFromString(template('Hello'), 'text/html');
const els = newNode.documentElement.querySelectorAll('div');
for (let index = 0; index < els.length; index++) {
  fragment.appendChild(els[index]);  
}
parent.appendChild(fragment);

由于文档片段位于内存中而不是主DOM树的一部分,因此在其上附加子代不会导致页面重排(元素位置和几何的计算).从历史上看,使用文档碎片可能会带来更好的性能.

Since the document fragment is in memory and not part of the main DOM tree, appending children to it does not cause page reflow (computation of element's position and geometry). Historically, using document fragments could result in better performance.

来源: https://developer.mozilla.org/en-US/docs/Web/API/Document/createDocumentFragment

基本上,您可以使用所需的任何模板,因为它只是一个可返回可输入解析器的字符串的函数.

Basically you can use whatever template you want because it's just a function that return a string that you can feed into the parser.

希望有帮助

这篇关于在不使用innerHTML的情况下在JavaScript中更改HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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