Here is an example where getElementById() and innerHTML are used to display debugging information in an HTML document. Suppose the document has the following div element:
Then the following function call would return a reference to that div:
Now suppose that you want to add some text to the debugDiv element. You can do so by using the innerHTML property as follows:
You can append text by using the += assignment operator:
Suppose that you wanted to display the value of a variable, name. You could use a line of code like this:
Using getElementById and innerHTML to add text to the debugging div takes two lines of code. Using basic DOM functions would require code to traverse the DOM tree, find the right element, create a new node, and append the new node to its parents list of child notes. That code could easily be five or ten times longer, and would be more difficult to understand, debug, and maintain.
When you set the value of the innerHTML property you can use
The browser will re-parse the element and format it accordingly, which is
powerful and dangerous.
It's powerful because you could build a table, or include a video player or
do anything else you can do with HTML.
It can be dangerous, however, if you put unfiltered user input into a
Doing so could the web page open to cross-site scripting attacks.
You can read about cross-site scripting attacks in this Wikipedia article:
and on this web site:
The Document Object Model (DOM) is a tree structure. (You can see an interactive diagram of a DOM tree structure here: https://gojs.net/latest/samples/DOMTree.html) Each node in the DOM tree is an object that has a property with a value that tells what kind of node it is. The most important kinds of nodes for our purposes are the document node, element nodes, attribute nodes, and text nodes.
The type of each node determines what kinds of nodes it can have as
Here is a summary of the parent-child relationships that are most important
for this class:
• A document node can have (at most) one element as a child.
• Elements can have other element nodes and text nodes as children.
• Text nodes don't have child nodes.
You can read more about node types on this w3schools page: https://www.w3schools.com/jsref/prop_node_nodetype.asp
In addition to the family-relationship terms mentioned in the book (parent, child, sibling), the terms ancestor and descendant are also used to describe relationships of nodes in a DOM tree.
Here's some code that demonstrates using document.createElement: