使用Javascript动态创建HTML元素? [英] Dynamically creating HTML elements using Javascript?

查看:66
本文介绍了使用Javascript动态创建HTML元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

}

我该怎么做?

推荐答案

您可以使用文档创建一个元素.createElement 。创建后,您可以添加属性。如果要在文档中显示该元素,则必须插入文档的DOM树。尝试玩这个代码:

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:

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

如果只是html,你希望这是一种方法:

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

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

另一种方法是创建一个div而不将其注入到DOM树中,并使用DOM方法添加元素。这里有一个创建1元素的功能

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

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>

这篇关于使用Javascript动态创建HTML元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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