NUS Hackers Wiki
NUS Hackers Wiki
  • NUS Hackers Wiki
  • Hackerschool
    • Virtual Machines and Linux
    • Beginners' Guide to the Terminal
      • Introduction to the Terminal
      • Modern Shell Tools
      • Shell Scripting
      • Real World Scripting
      • Resources
    • Self-Hosting: Three Easy Pieces
      • 1. Setting up your server
      • 2. Running Services
      • 3. Monitoring your server
    • Vim
    • Introduction to Zig
      • Language Basics
      • Error Handling
      • Memory Management
      • Working with C
      • Exploring comptime
    • CI/CD with Github Actions
      • Background
      • Basics of Github Actions
        • Target workflow
        • Running unit tests
        • Linting code
        • Deploying to Github Pages
      • Advanced use cases
        • Pollers
        • Github script
        • Executing third-party scripts
        • Reusable workflows
      • Cookbook
    • Lightning Git
      • Git Concepts
      • Getting Started with Git
      • Making your first commit
      • Branching
      • Merge Conflicts
      • Integrating remote repositories
      • Collaborative Workflows
      • Commit Manipulation and Reflog
      • Interactive rebasing
      • filter-repo
  • Orbital
    • JavaScript
      • Browser Developer Tools
      • Getting Started
      • Datatypes
      • Operators and Operations
      • Loops and Conditions
      • Functions
      • Strings
      • Arrays
      • HTML
        • Getting Started
        • Tag Attributes
        • HTML Forms
        • Browser Inspector
      • CSS
        • Selectors
        • Colors in CSS
        • Measurements in CSS
        • The Box Model
        • Adding Styles - Part 1
        • Adding Styles - Part 2
      • Working with the DOM
        • Querying the DOM - Selectors
        • Querying the DOM - Element Attributes
        • Querying the DOM - Element Styles
        • Events with JS and HTML
        • Exercise: Click Counter
        • Editing the DOM
        • Fetch Requests
        • Exercise: The NUSMods API
    • React
      • Setup
      • State
    • React Native
      • Setup
      • Intro to JSX
      • Basic Syntax
      • Handling UI
      • Props
      • State Management
    • Git
      • Setup
      • Command Glossary
      • Fundamental Concepts
        • Getting Started
        • Integrating Remote Repositories
        • Branching
        • Merge Conflicts
      • Collaborative Workflows
        • Fork and PR Workflow
        • Branch and PR Workflow
      • Advanced Concepts
        • Ignoring Files
        • Commit Message Conventions
        • Github Collaborators
        • CI/CD with Github Actions
        • Advanced Git Commands
      • FAQ
    • Telegram Bot
      • Creating a TeleBot
      • API Calls
      • Telebot Basics
      • Integrating API's
    • Relational Database
      • Database Overview
      • Database Design
      • Entity Relationship Diagram
      • SQL Basics & PostgreSQL
    • TypeScript
      • Types and Interfaces
      • Utility Types
      • Typing Component Props, Events, and Hooks
      • Why You Should Avoid Using any (and What to Do Instead)
      • TypeScript Tricks You’ll Use All the Time in React
Powered by GitBook
On this page
  • Creating elements
  • Setting attributes
  • Adding text
  • Adding elements to the page
  • Insert before
  • Insert at the end
  • Removing elements from the page
  • Replace one element with another
  • Next steps
Edit on GitHub
Export as PDF
  1. Orbital
  2. JavaScript
  3. Working with the DOM

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:

let newElement = document.addElement("a");
newElement.setAttribute("className", "purple-link");
newElement.setAttribute("href", "https://orbital.comp.nus.edu.sg/");
newElement.innerText = "Link to Orbital page";

The second way is to create a special element, called a Text Node, and add that to the element:

let newElement = document.addElement("a");
newElement.setAttribute("className", "purple-link");
newElement.setAttribute("href", "https://orbital.comp.nus.edu.sg/");
let text = document.createTextNode("Link to Orbital Page");
newElement.appendChild(text); // see below on how to add elements to the page

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:

let tag1 = document.createElement("div"); // new element we make
let tag2 = document.getElementById("tag2"); // already present on page
document.body.insertBefore(tag1, tag2); // tag1 inserted before tag2 in the body

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:

let newChild = document.createElement("div"); // new element to make
let otherChild = document.getElementById("other-child"); // element to insert before
let parent = document.getElementById("parent"); // element to insert inside of
parent.insertBefore(newChild, otherChild);

The above code will turn this:

<div id="parent">
    <div>Thing</div>
    <div>Thing again</div>
    <div id="other-child">Something</div>
    <div>Something again</div>
</div>

Into this:

<div id="parent">
    <div>Thing</div>
    <div>Thing again</div>
    <div></div> <!-- the new element we made -->
    <div id="other-child">Something</div>
    <div>Something again</div>
</div>

Insert at the end

To insert an element at the end of a parent element, using the appendChild method:

let newChild = document.createElement("div"); // new element to make
newChild.innerText = "Child 5"; // add some text
let parent = document.getElementById("parent"); // element to insert inside of
parent.appendChild(newChild);

The above code will turn this:

<div id="parent">
    <div>Child 1</div>
    <div>Child 2</div>
    <div>Child 3</div>
    <div>Child 4</div>
</div>

Into this:

<div id="parent">
    <div>Child 1</div>
    <div>Child 2</div>
    <div>Child 3</div>
    <div>Child 4</div>
    <div>Child 5</div>
</div>

Removing elements from the page

Let's say we select an element that we want to remove from a page:

let elementToRemove = document.getElementById("remove-this");

First, we need its parent element:

let parentElement = document.getElementById("parent");

Then we can use the removeChild method:

parent.removeChild(elementToRemove);

Replace one element with another

To replace one element with another, use the replaceChild method:

let newChild = document.createElement("div");
let oldChild = document.getElementById("old-child");
let parent = document.getElementById("parent");
parent.replaceChild(newChild, oldChild);

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.

PreviousExercise: Click CounterNextFetch Requests

Last updated 12 months ago