JavaScript DOM manipulation
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
innerHTML
innerText
- Creating and appending new objects (i.e. new HTML tags)
appendChild
createElement
- Selecting and removing objects
querySelector
removeChild
- 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:
document.body.innerHTML = "<p>hi</p>"
For this HTML page:
<html>
<head>
<script src="index.js"></script>
</head>
<body>
<div id="app">hey</div>
<div id="bar">x</div>
</body>
</html>
...if we load up index.html, the entire webpage will show just:
hi
Applying 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:
document.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:
hey
yo
innerText
For whatever reason, we can use innerText
if we don't want to strip away the HTML tags in the browser:
document.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:
const paragraph = document.createElement('p')
paragraph.textContent = 'Cake'
document.body.appendChild(paragraph)
// <p>Cake</p>
Selecting and removing objects
querySelector
We can also point to an element with document.querySelector
:
- this
document.querySelector
then 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:
const blueSection = document.querySelector('section.section-blue')
document.body.removeChild(blueSection)
Setting element attributes
setAttribute
We can use the setAttribute
method to update the attribute values of an HTML tag:
const myParagraph = document.getElementById("myparagraph")
myParagraph.setAttribute("class", "myClass")
...for an HTML line such as this:
<p id="myparagraph">Hi</p>