I have written a post on innerHTML not to long ago which is one typical way of adding elements once a reference to a container element is obtained. However in this post I will be covering the subject in general, and not just the use of innerHTML which might not always be the best choice. There are of course alternatives to innerHTML that involve the use of a collection of methods, such as createElement, and appendChild.
The innerHTML property of an element object is one way to go about getting a string value of the innerHTML of an element, but it can also be used to set the innerHTML also with a string value of the desired innerHTML.
In this post I am not going to be going into detail about innerHTML as I have written a post on that all ready. However innerHTML is of course one option for making quick work of this when it comes to simple projects. When it comes to more advanced projects though there are some situations in which an alliterative way of doing this should be used.
So now that we have a very basic idea of what this is all about otu of the way I can now move on to other ways of adding elements to an html document.
The alternative to using innerhtml as a way to create elements is to use the document.createElement method along with something like appendChild, and createTextNode. This is generally the preferred way to create and add new elements into an html document because it allows for access to element object reference right away. In addition I can set all kinds of properties to the created element before appending it the the html, or I can even not append it at all if I find that I do not want to for whatever the reason.
2 - The createTextNode method and creating paragraph elements, and any element that might require a text node
Some elements such as a p, span, and pre might require a text node value added to after creating it in order for the element to actually show some text. So in this section I think that it is called for to cover a few quick examples that have to do with adding text nodes to newly created elements with the create element method.
So for starters there are paragraph elements, and when creating them it is often called for to define what the value of the text node is for that element. One way to do so it to use the createTextNode method to create a text node with the desired text, and then append that to the newly created paragraph element.
There is more than one kind of line break depending on the operating system, but for the most part it is best to just go with the windows style one that contains a carriage return and then a line feed after. the reason why I say that it that that kind of line break will work o windows but will also work okay on just about every other operating system just fine also.
An example such as this could be expanded with additional methods to make a simple grid system, but this alone should help with the general idea of why it is that pre elements are useful in some situations.