Why use JS to add elements instead of modifying the HTML script?


I’m currently doing some examples involving creating, inserting, replacing and removing elements. I understand why you might want to change something as a reaction to user input (ex: button click) but is there any other reason you would want to use these? Is it that big of a deal to go back into the HTML file and modify/add elements instead of using JS?


The concept is called DOM insertion. It is a process of modifying the HTML page (document) in memory so changes are dynamicly updated on the next screen redraw. (Screen refresh occurs in excess of 70 times per second.)

It is not possible to alter the source HTML, only the DOM tree which contains all the nodes parsed from the source document. Whatever happens after that can only be seen on inspection, not view source code.

The document sent down from the server is said to be static in nature. It is the model from which the document tree is constructed. Script is how we make any dynamic changes in how the page presents to the user, and how it behaves.

We can leverage JS on the client side by having it pull down other API resources so they don’t have to be installed in the response document that PHP. Django, Rails, &c. send down from the server.

Bottom line, we cannot edit the source document on the fly. Only the DOM tree can be modified. What changes is the rendered view for the user.