DOM Manipulation Revision/Cheat Sheet
Selecting
The only two selector methods you need:
querySelectorquerySelectorAll
const container = document.querySelector('.container')
console.log(container)
const listItems = document.querySelectorAll('li')
console.log(listItems)Relative Selecting
You can call the selector methods from any element not just from document.
const container = document.querySelector('.container')
const h1sInContainer = container.querySelectorAll('h1')Traversal
childrenparentElementnextElementSiblingpreviousElementSibling
.children is an HTMLCollection which is an array-like object. You can access its elements with bracket syntax [] and loop over it with for loops.
Changing Content
textContentinnerHTML
.innerHTML will turn the HTML tags in the string into DOM elements.
Manipulating Styles
NOTE: Hyphenated CSS property names are in the style object as camelCase.
Manipulating CSS Classes
classlist.addclasslist.removeclasslist.toggle
Instead of adding styles to the style object directly, you can write the style rules in a css file under a class name that you will then apply to the element in the DOM.
Add classes
Remove classes
Toggle classes
If the element already has the selected class, .toggle will remove it, otherwise it will be added.
Add And Remove Multiple Classes
Manipulating Attributes
In most cases you can just use the DOM element's corresponding property. Read more here for when property and attribute are synced.
You can change these values using the assigment operator =:
Data Attributes
Creating New Elements
document.createElement
Inserting Elements
appendprependafterbefore
.append
Adds elements to the end of the parent element's list of children.
.prepend
Adds elements to the beginning of the parent element's list of children.
.after
Adds elements as siblings after the element its called on.
.before
Adds elements as siblings before the element its called on.
Removing Elements
removeChildremove
.removeChild
.remove
This is a newer (better?) method but is unsupported in Internet Explorer.
Event Listeners
addEventListener
Last updated
Was this helpful?