使用 Javascript 动态创建 HTML 元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5536596/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:42:37  来源:igfitidea点击:

Dynamically creating HTML elements using Javascript?

javascripthtmldom

提问by dojoX

I want to dynamically create some HTML elements (3 html element) and then return this html code as a string in a variable. I don't want to write the HTML code in the following function to some div, but, I want to return it in a var.

我想动态创建一些 HTML 元素(3 个 html 元素),然后将此 html 代码作为变量中的字符串返回。我不想将以下函数中的 HTML 代码写入某个 div,但是,我想在 var 中返回它。

function createMyElements(id1,id2,id3){

   //create anchor with id1
   //create div with id 2
   //create xyz with id3

  //now return the html code of above created just now

}

How can I do this?

我怎样才能做到这一点?

回答by KooiInc

You can create an element using document.createElement. After creation you can add attributes. If you want the element to show up in your document, you have to insert in into the DOM-tree of the document. Try playing around with this code:

您可以使用document.createElement. 创建后,您可以添加属性。如果您希望元素显示在您的文档中,您必须将 in 插入到文档的 DOM 树中。尝试使用以下代码:

var body = document.getElementsByTagName('body')[0],
    newdiv = document.createElement('div');   //create a div
    newdiv.id = 'newid';                      //add an id
    body.appendChild(newdiv);                 //append to the doc.body
    body.insertBefore(newdiv,body.firstChild) //OR insert it

If it's only html you want this is an approach:

如果它只是你想要的 html,这是一种方法:

function createmyElements(id1,id2,id3){
   return [
           '<a href="some link" id="',
            id1,
           '">linktxt</a>',
           '<div id="" ',
            id2,
           '"></div>',
           '<someElement id="',
            id3,
           '"></someElement>'
          ].join('\n');
}

Yet another approach is to create a div without injecting it into the DOM tree and add elements to that using DOM methods. Here's a function to create 1 element

另一种方法是创建一个 div 而不将其注入 DOM 树并使用 DOM 方法向其添加元素。这是一个创建 1 个元素的函数

function createElementHtml(id,tagname){
  var containerdiv = document.createElement('div'),
      nwtag = document.createElement(tagname);
  nwtag.id = id;
  containerdiv.appendChild(nwtag);
  return containerdiv.innerHTML;
}
//usage
createElementHtml('id1','div'); //=> <div id="id1"></div>

回答by Guidhouse

Html:

网址:

<div id="main"></div>

JavaScript:

JavaScript:

var tree = document.createDocumentFragment();
var link = document.createElement("a");
link.setAttribute("id", "id1");
link.setAttribute("href", "http://site.com");
link.appendChild(document.createTextNode("linkText"));

var div = document.createElement("div");
div.setAttribute("id", "id2");
div.appendChild(document.createTextNode("divText"));

tree.appendChild(link);
tree.appendChild(div);
document.getElementById("main").appendChild(tree);

The main reason to use a documentFragment in stead of just adding the elements directly is speed of execution.

使用 documentFragment 而不是直接添加元素的主要原因是执行速度。

At this size it doesn't matter, but when you start adding hundreds of elements, you will appreciate doing it in-memory first :-)

在这个大小上没关系,但是当您开始添加数百个元素时,您会很高兴首先在内存中进行:-)

With documentFragment you can construct a whole tree of DOM-elements in-memory and will not afffect the browser DOM untill the last moment.

使用 documentFragment,您可以在内存中构建一棵完整的 DOM 元素树,并且直到最后一刻才会影响浏览器 DOM。

Otherwise it forces the browser to update for every element, which sometimes can be a real pain to watch.

否则它会强制浏览器为每个元素更新,这有时会很痛苦。

回答by parasrish

Here's simple illustration for converting the html-page (static), to javascript based html-page (dynamic).

这是将 html 页面(静态)转换为基于 javascript 的 html 页面(动态)的简单说明。

Let us say, you have html-page as "index.html" (calling index_static.html here).

让我们说,你有 html-page 作为“index.html”(在这里调用 index_static.html)。

index_static.html

index_static.html

<!DOCTYPE HTML>
<html>
    <head>
        <title>Test</title>
    </head>
    <body>
        <h1> Hello !!! </h1>
    </body>
</html>

You can open this file in the browser, to see the desired output.

您可以在浏览器中打开此文件,以查看所需的输出。

Now, lets create a javascript equivalent to this. Use online-tool, to generate the javascript source (by pasting the above html file source to it). Therefore, it follows as:

现在,让我们创建一个与此等效的 javascript。使用online-tool生成 javascript 源代码(通过将上面的 html 文件源粘贴到其中)。因此,它如下:

dynamic.js

dynamic.js

document.write("<!DOCTYPE HTML>");
document.write("<html>");
document.write("    <head>");
document.write("        <title>Test<\/title>");
document.write("    <\/head>");
document.write("    <body>");
document.write("        <h1> Hello !!! <\/h1>");
document.write("    <\/body>");
document.write("<\/html>");

And now, your dynamic version of the static_index.html will be as below:

现在,您的 static_index.html 动态版本将如下所示:

index_dynamic.html

index_dynamic.html

<script language="JavaScript" src="dynamic.js"></script>

Open the index_dynamic.html on the browser to validate the web-page (dynamic though, down-the-line).

在浏览器上打开 index_dynamic.html 以验证网页(尽管是动态的,下线)。

more info

更多信息

回答by Sufendy

You can construct the html as a string in one variable like

您可以将 html 构造为一个变量中的字符串,例如

var html = "";
html += "<a id='" + id1 +"'>link</a>";
html += "<div id='" + id1 +"'>div</div>";
// ... and so on

then you return the variable html

然后你返回变量 html

return html;

回答by akinuri

If you're doing this repeatedly (dynamically creating HTML), you might want to use a more general approach.

如果您重复执行此操作(动态创建 HTML),您可能需要使用更通用的方法。

If you want to create three unrelated elements, you can do:

如果要创建三个不相关的元素,可以执行以下操作:

var anchor = elem("a", {"id":"id1"});
var div    = elem("div", {"id":"id2"});
var xyz    = elem("div", {"id":"id3"});

Now, you have three elements. If you want to get the HTML of these (as string), simply do:

现在,您拥有三个元素。如果您想获取这些的 HTML(作为字符串),只需执行以下操作:

var html = anchor.outerHTML + div.outerHTML + xyz.outerHTML;

If you want to have these three in an element (say, div), do:

如果你想在一个元素中包含这三个(比如 div),请执行以下操作:

var div = elem("div", null, [
    elem("a", {"id":"id1"}),
    elem("div", {"id":"id2"}),
    elem("div", {"id":"id3"}),
]);

You can get the HTML with div.outerHTML, or you can just append it anywhere you want.

您可以使用 获取 HTML div.outerHTML,也可以将其附加到您想要的任何位置。

To know more about elem(), visit element.js (GitHub).

要了解有关 的更多信息elem(),请访问element.js (GitHub)



I'm adding this answer not for the 8 year old question, but for the future visitors. Hope, it helps.

我不是为 8 岁的问题添加这个答案,而是为未来的访问者添加这个答案。希望能帮助到你。