While developers should keep to the ideals of progressive development as much as possible when using JavaScript, there are absolutely times that we must create elements ex nihilo. Often these are elements that depend on JavaScript for their functionality, and therefore should be created with JavaScript:

虽然开发商应保持考试的理想逐步发展使用时尽可能JavaScript ,有绝对的时间,我们必须创建元素无中生有 。 通常,这些元素依赖于JavaScript的功能,因此应使用JavaScript 创建

召唤 (The Summoning)

We can create any kind of HTML element using document.createElement and the tag name:

我们可以使用document.createElement和标记名称创建任何类型的HTML元素 :

var newAside = document.createElement("aside");

At this point, the element is simply floating in the aether: it’s not yet part of our page. There are many ways of doing just that, but perhaps the easiest is using appendChild:

在这一点上,该元素只是在以太中浮动:它还不是我们页面的一部分。 这样做有很多方法,但是也许最简单的方法是使用appendChild

document.body.appendChild(newAside);

There are a few things to note:

有几件事要注意:

  • you can’t currently add an attribute to the element at the same moment it is created; you must use setAttribute or a related method on a separate line of JavaScript.

    您目前无法在元素创建的同时将属性添加到元素; 您必须在另一行JavaScript上使用setAttribute或相关方法。

  • you may feel compelled to add an id to the element, but it’s unlikely that you need to do so: you already have a reference to the element in the newAside variable.

    您可能会被迫向该元素添加id ,但是不太可能需要这样做:您已经在newAside 变量中对该元素进行了newAside

  • once you add it to the page, the new element will follow any presentation rules applied to it via a CSS stylesheet.

    将其添加到页面后,新元素将遵循通过CSS样式表应用于该元素的所有展示规则。

此代码与insertAdjacentHTML有什么区别? (What’s the difference between this and insertAdjacentHTML?)

Since they both ultimately achieve the same ends of putting elements on a page, it might be tempting to believe that document.createElement and insertAdjacentHTML are the same, but there are significant differences. Most importantly, insertAdjacentHTML takes a string of characters that JavaScript parses into HTML, whereas document.createElement creates a node with a variable that can be referenced later.

由于它们最终都达到了在页面上放置元素的相同目的,因此很可能会相信document.createElementinsertAdjacentHTML是相同的,但是存在显着差异。 最重要的是, insertAdjacentHTML接受JavaScript 解析为HTML的字符串 ,而document.createElement创建一个带有变量的node ,该变量以后可以引用。

翻译自: https://thenewcode/1087/The-Act-of-Creation-Making-New-Tags-with-documentcreateElement

更多推荐

创建行为:使用document.createElement制作新标签