javascript and divs, creating images and paragraphs in divs.
html, javascript
Solution
In its simplest form:
// 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.
References:
- `element.appendChild()`.
- `document.createElement()`.
- `document.createTextNode()`.
Problem
Im trying to do some basic stuff with javascript, to get it to generate some website content automatically,, but its driving me crazy!!! Could someone please show me a simple example of how to do get javascript to create new images and paragraphs in divs.. lets say my website structure is like this... ``` <html> <head> </head> <body> <div id ="wrapper"> <div id ="content"> </div> </div> </body> </html ``` how would I use a javascript function to create images and paragraghs in the "content" div on-loading the page and also on-clicking an image. I know it has to with the DOM but Ive been at this for hours and I just cant get it to work! Please show me an example of how its done. Thanks a lot in advance!!!!!!