javascript和divs,在div中创建图像和段落。

时间:2012-06-02 20:52:24

标签: javascript html

我试着用javascript做一些基本的东西,让它自动生成一些网站内容,但它让我疯狂!有人可以告诉我一个简单的例子,说明如何使用javascript在div中创建新的图像和段落..让我说我的网站结构是这样的......

<html>
<head>
</head>

<body>
<div id ="wrapper">
<div id ="content">
</div>
</div>
</body>
</html

我如何使用javascript函数在“content”div中创建图像和段落加载页面以及点击图像。我知道它与DOM有关,但我已经在这几个小时,我不能让它工作!请告诉我一个如何完成它的例子。非常感谢提前!!!!!!

1 个答案:

答案 0 :(得分:5)

最简单的形式:

// gets a reference to the div of id="content":
var div = document.getElementById('content'),
    // creates a new img element:
    img = document.createElement('img'),
    // creates a new p element:
    p = document.createElement('p'),
    // creates a new text-node:
    text = document.createTextNode('some text in the newly created text-node.');

// sets the src attribute of the newly-created image element:
img.src = 'http://lorempixel.com/400/200/people';

// appends the text-node to the newly-created p element:
p.appendChild(text);

// appends the newly-created image to the div (that we found above):
div.appendChild(img);
// appends the newly-created p element to the same div:
div.appendChild(p);

JS Fiddle demo

参考文献: