Topic 6: DOM Manipulation

What is DOM?

DOM stands for Document Object Model. After the HTML page is loaded, the browser will create something called a Document Object Model of the page. This is what an example HTML DOM Tree of Objects looks like:

HTML DOM Tree of Objects Diagram

Within this model, it shows the document as the head element, then everything within html is the root element. This is further divided into the head element and the body element. Then each element inside of these tags is broken down.

By creating this object model, you can access any individual object using JavaScript to create, read, update, or delete elements and attributes within the HTML file. This becomes extremely useful when you want to make a static HTML page more dynamic.

I will explore some of the things you can do to manipulate HTML using JavaScript in the next few sections. Topic 7 shows how to use JavaScript to manipulate CSS class properties.

Resources



The createElement() method does exactly what it describes. It can create a new HTML element to insert into the page.

Example

In this example, when the button is pressed, an image will appear.

Resources


The appendChild() method appends or attaches a specified element to the last child. In the previous example, I appended the picture of the dog to the body which means that it will be placed at the end of the document. For this example I will do something a little different and append an element to something with an ID.

Example

In this example I will create a button that triggers a function which will append a figCaption to the figure.

Resources


The removeChild method will remove a specific child node which can be determined by the index number.

Example

In this example, when the button is pressed, an item in the list will disappear.

It is important to note that all of the items of the unordered list are placed on the same line with no whitespace in between each item. This is because the white space will be counted as a child node which doesn't agree with the index count of the list.

Resources


This is my teaching video. It starts at 0:00 and ends at 3:46