JavaScript DOM manipulation
// updated 2025-05-07 15:58
In the last page where we covered JavaScript DOM access, we merely obtained the webpage objects but we did not alter any of them. In this page, we will discuss JavaScript DOM manipulation, which includes:
- Manipulating text
innerHTMLinnerText
- Creating and appending new objects (i.e. new HTML tags)
appendChildcreateElement
- Selecting and removing objects
querySelectorremoveChild
- Setting element attributes
setAttribute
Manipulating text
For any document object, we would manipulate its text by using one of three methods (depending on our formatting needs):
innerHTML
We can use innerHTML to change the contents inside any HTML tag:
1document.body.innerHTML = "<p>hi</p>"For this HTML page:
1<html>
2
3 <head>
4
5 <script src="index.js"></script>
6
7 </head>
8
9 <body>
10
11 <div id="app">hey</div>
12
13 <div id="bar">x</div>
14
15 </body>
16
17</html>...if we load up index.html, the entire webpage will show just:
1hiApplying innerHTML on the entire <body> tag replaces the entire contents of the tag. The browser then formats whatever HTML accordingly, so the browser will show only the "inner" part of the HTML tag.
Also, for the above HTML page example, we can use document methods to reach any element:
1document.getElementById('bar').innerHTML = 'yo'This will then make the browser modify only the inner contents of the tag with an id value of bar, yielding:
1hey
2yoinnerText
For whatever reason, we can use innerText if we don't want to strip away the HTML tags in the browser:
1document.body.innerText = "<p>Hi</p>"...the full string, including the HTML tags, will also show on the browser!
Creating and appending new objects
appendChild and createElement
We can use the createElement method to create an HTML/DOM object. The element's appendChild built-in method then appends (or adds) the HTML/DOM object onto a would-be "parent" node:
1const paragraph = document.createElement('p')
2paragraph.textContent = 'Cake'
3document.body.appendChild(paragraph)
4// <p>Cake</p>Selecting and removing objects
querySelector
We can also point to an element with document.querySelector:
- this
document.querySelectorthen takes an argument (a string) that resembles the notation of a CSS selector- e.g.
.my-class,#someId,section.section-blue
- e.g.
removeChild
We can use the removeChild method, on document.body, to delete any document object from the DOM:
1const blueSection = document.querySelector('section.section-blue')
2document.body.removeChild(blueSection)Setting element attributes
setAttribute
We can use the setAttribute method to update the attribute values of an HTML tag:
1const myParagraph = document.getElementById("myparagraph")
2myParagraph.setAttribute("class", "myClass")...for an HTML line such as this:
1<p id="myparagraph">Hi</p>