Creating and appending an element is just one way to change the DOM and be able to dynamically change your application. To dynamically change is to add things to the DOM without having to change the html files. We could be accessing information from another api and filling information on our site or we could be taking user input and displaying that data based on each users answers.
First we can open up the console by using the shortcut command-option-j for mac users. Once in the console tab of our dev tools we can create an element that we later want to append to the page. .createElement is a method built in to the document that you have access to once in the console.
I’ve created a list element that I will be adding items to in the future. We can then start building out that element by giving it some text or html, or both.
By calling that element and using the .innerHTML method we are able to both write some HTML that the page will render as well as put text inside of our element.
Calling on that “li” element now will show the value you assigned in the previous step when you defined its innerHTML.
After we create an element and define what we want inside of that element we need to figure out where on the page, or in the application, we want this new information to be displayed.
Using a .querySelector we are able to assign the space we want to manipulate its own variable. ***A querySelector() will return the first instance of the condition you set. If you wish to see all ‘h3’s you should use the .querySelectorAll(). If you wish to find a specific id you can search the document with .getElementById().
Now that we have the space we want to manipulate and the element we want to put to the screen we can put those two together. We do this by appending our created element to the selected space on the document.
Using the .appendChild method called on our selected document object we are able to pass the argument of our created element and see those changes reflected in the console and on the screen!
- **If you have more than one element to append , .appendChild() will not work. For multiple appends use, .append().
- This is only the beginning and it is not the only way to do things with the DOM. We have many options from here. We could give our list an id, grab it from the document, and add new elements to that element. We could git rid of our list completely. We could even have made an entire list before we appended it to the page. Be curious. Play around with it.