Generating HTML using JavaScript

Using the DOM hierarchy, we can add element, attribute, and text nodes anywhere in the head or body sections of a document. In this chapter you'll learn how to create a paragraph node, give it an attribute, and fill it with text content. In the next chapter, you'll learn how to insert the paragraph, along with its attributes and text content, into the page.

The first step is to create the paragraph node.

var nodeToAdd = document.createElement("p");

The example creates a paragraph element. To create a div element, you'd put "div" in the parentheses. To create an image element, you'd put "img" there. To create a link, you'd put "a" there. And so on.
Here's a statement that creates an image element.

var imgNodeToAdd = document.createElement("img");

we can also add attribute to an HTML element using  setAttribute. we can do the same thing with an element that we have created but haven't yet placed in the document body.

nodeToAdd.setAttribute("class", "regular");

The code above gives the new paragraph element that you just created the class "regular". If we wanted to, we could add, using separate statements for each, more attributes to the paragraph element—for example, a span, a style, even an id.

If the element were an <img> element, you could add a border or an alt as an attribute. If it were an <a> element, you could add the web address. This statement adds a border attribute to an image element.

imgNodeToAdd.setAttribute("border", "1");

The code above gives the image a 1-pixel border.

Remember, at this point, we're just creating nodes. The new attribute node has been connected to the new element node, but we haven't added the nodes to the page yet. Getting back to the paragraph element, we've created it and added a class attribute to it. Now let's give it some text content. Again, we begin by creating the node we want.

var newTxt = document.createTextNode("Hello!");

The statement above creates a text node with the content "Hello!" Next, we place the text into the paragraph element.

nodeToAdd.appendChild(newTxt);
 
The statement above adds the new text node, whose content is "Hello!", to the new paragraph node.
Now we have a new paragraph node with a class attribute and some text content. We're ready to insert it into the page.