Generating Content

When your content is minimal, you manually assemble it in an HTML file. But when the content is generated by algorithms and drawn out of other storage systems, you probably want to craft the HTML in other ways. JavaScript provides several means of generating HTML algorithmically.

To append new content at the end of an HTML file, you use document.write:

html
js
preview

Usually, however, you want to update the content of some existing element in the document. To do that, you give the element an id and then ask the document for a reference to that element's entry in the document object model (DOM) using getElementById. To update the element's plain text content, you assign to its innerText property:

html
js
preview

The function getElementById finds the single element in your document that has the given ID. If you wish to grab references to several elements, you may use getElementsByTagName or getElementsByClassName. Both of these expect you to pass the tag name or class name as a parameter. If your search criteria is more complex, you may use querySelectorAll, which expects an arbitrary selector just like you would use in CSS. For example, to select just the list items in the vowels list, you write this query:

html
js
preview

If the generated content contains HTML that you want the browser to interpret, you assign to its innerHTML property:

html
js
preview

The content generation methods described above expect you to compose the content in a string. JavaScript also provides routines for directly creating and manipulating elements without resorting to strings. You create a new element with createElement and a new text node with createTextNode. You attach a child to its parent with appendChild. For example, this code appends an anchor to the body element:

html
js
preview

An element's individual attributes are set using setAttribute. Try adding a text input after the anchor.

Suppose you wanted a list of links to all two-letter domains on the web. That's something you'd never want to write by hand in HTML. But with JavaScript, you may generate the list procedurally:

html
js
preview

There is no guarantee that those links are valid or safe to browse.