Create a new page called addchild.html. Put this HTML inside the body element (under the main heading):
<p onmouseup="addMoreParagraphs();">Add more paragraphs by clicking here</p>
then put this JavaScript inside the script element:
function addMoreParagraphs() {
var newElement=document.createElement('p');
newElement.textContent='Hi';
document.body.appendChild(newElement);
}
Try it and a paragraph should be created with the lines of JavaScript doing this:
- create a new element (called newElement but it could have been called anything) of the type p (the element is created as a JavaScript object not in the page at this stage)
- change (add) the content of the element
- add the element to the page as a child of the body element
You can also add attributes to the element before creating it. Add this line of code before the current appendChild line:
newElement.setAttribute('style', 'color:#D400D4');
The element now has in-line styles. You could set a class, id or an event trigger in the same way.
You do not need to add the new element to body. You can add it as a child to anything (maybe using getElementById).