Editing the DOM
We've so far seen how to query and update the DOM, but JS allows us to create and delete elements as well.
Creating elements
To create an element, simply use the document.createElement method, passing in the tag name:
let newElement = document.addElement("a");The above line creates a new <a> element.
Setting attributes
When a new element is made, it is a raw element with no attributes. However, we can use the same methods as earlier to set attribute values for the element:
newElement.className = "purple-link";
newElement.href = "https://orbital.comp.nus.edu.sg/";The second way is to use the setAttribute method:
newElement.setAttribute("className", "purple-link");
newElement.setAttribute("href", "https://orbital.comp.nus.edu.sg/");Both methods have the same result, but it is convention to use the second method when new attributes are being added to an element.
An element's styling can be changed the same way as before, using the style attribute.
Adding text
To add some text inside a newly created method, you can use one of two methods. The first involves the innerText property:
The second way is to create a special element, called a Text Node, and add that to the element:
Adding elements to the page
Once the element has been created, it is time to add it to the page so it renders. There are a number of ways to do this, depending on where on the page the element has to go.
Insert before
If the new element has to be inserted before an existing one, then the insertBefore method is useful:
If the new element has to be inserted before an existing one inside some parent element that is not the body, the following code will work:
The above code will turn this:
Into this:
Insert at the end
To insert an element at the end of a parent element, using the appendChild method:
The above code will turn this:
Into this:
Removing elements from the page
Let's say we select an element that we want to remove from a page:
First, we need its parent element:
Then we can use the removeChild method:
Replace one element with another
To replace one element with another, use the replaceChild method:
Next steps
Next, we'll look at fetch requests and how they can retrieve information without having to reload the page. We'll do so with an example of the NUSMods API.
Last updated