JavaScript DOM manipulation
making changes to the HTML with JavaScript
Manipulating text
(innerHTML)
Finally, now for some interesting stuff: we can use the innerHTML
property to manipulate the content of each DOM object, for example:
If we load up index.html
the entire webpage will show just:
...as we have just replaced the entire document's body to consist of only that string!
Manipulating objects
(getElementById)
Now that we know how to manipulate the document's body, we should know how to manipulate its objects:
Loading up index.html
the webpage will display:
Note that it will replace only the first <div>
because we specified to get the <div>
with the id
of app
and not bar
Creating and appending objects
(appendChild and createElement)
We can:
create elements with the
document.createElement
functionappend them using the
document.body.appendChild
function
...and we can chain them as such:
Selecting and removing objects
(querySelector and removeChild)
Likewise, we can:
point to an element with
document.querySelector
querySelector
takes one String parameter that resembles the notation of the CSS selector, e.g..my-class
,#anId
,section.section-blue
delete objects from the DOM using
document.body.removeChild
Last updated