logo
logo

DOM Cheatsheet

Accessing the DOM

JavaScript can access the DOM using the global variable
document
, which represents the entire HTML document. The
document
object provides many built-in methods that allow developers to access specific nodes and elements within the DOM.
For example, to access an element with a specific ID, you can use the
getElementById()
method, which returns the element with the matching ID:
const element = document.getElementById('myElement');
Similarly, the
getElementsByClassName()
method returns an array-like collection of elements with the matching class name:
const elements = document.getElementsByClassName('myClass');
The
getElementsByTagName()
method returns a collection of elements with the matching tag name:
const elements = document.getElementsByTagName('div');
You can also use the
querySelector()
and
querySelectorAll()
methods to select elements using CSS-style selectors:
const element = document.querySelector('#myElement');
const elements = document.querySelectorAll('.myClass');

DOM Traversal

DOM traversal allows developers to navigate the DOM tree and locate specific nodes for manipulation. Each node in the DOM is represented as an object, with properties that can be accessed and modified.

For example, to access the parent node of an element, you can use the
parentNode
property:
const parent = element.parentNode;
Similarly, the
childNodes
property returns an array-like collection of a node's child nodes:
const children = parent.childNodes;
To access the first child or last child of a node, you can use the
firstChild
and
lastChild
properties:
const firstChild = parent.firstChild;
const lastChild = parent.lastChild;
You can also access the next and previous sibling nodes using the
nextSibling
and
previousSibling
properties:
const next = element.nextSibling;
const prev = element.previousSibling;

Altering HTML Content

JavaScript can be used to alter the inner HTML of an element, providing a powerful way to dynamically update the content on a web page. To change the inner HTML of an element, you can simply assign a new value to the
innerHTML
property:
element.innerHTML = '<p>New content</p>';
You can also use the
createTextNode()
and
appendChild()
methods to add new content to an element:
const textNode = document.createTextNode('New content');
element.appendChild(textNode);

The HTML Collection

The HTML collection is an array-like structure that contains the HTML elements on a web page. Developers can access and manipulate specific nodes within the collection using their tag name or index.

For example, to access the second
div
element on a page, you can use the
item()
method of the HTML collection:
const element = document.getElementsByTagName('div').item(1);

Or, you can use array-style bracket notation:

const element = document.getElementsByTagName('div')[1];

Getting Elements by ID

To get an HTML element by ID in JavaScript, you can use the
getElementById
method. This method takes one argument, which is the ID of the element you want to retrieve. Here's an example:
const element = document.getElementById("myId");
This will return the element with the ID of "myId". If no element is found, it will return
null
.

Doing Subqueries

Sometimes, you may want to perform an operation on specific elements that are children of a parent element. To do this, you can use subqueries. Here's an example:

const parent = document.getElementById("parentElement");
const children = parent.getElementsByTagName("div");
This will return an HTML collection of all the
div
elements that are children of the element with the ID "parentElement".

Changing the Text or Content of an Element

To change the text or content of an element in JavaScript, you can use the
innerHTML
property. Here's an example:
const element = document.getElementById("myId");
element.innerHTML = "New text";

This will change the text inside the element with the ID "myId" to "New text".

CSS Selectors

CSS Selectors are used to grab parts of your HTML and style them. You can select elements using their tag names, classes, and IDs. For example, to select a div with a specific class, you can use a dot followed by the class name like this:

.dummy {
  color: red;
}

Query Selector and Query Selector All

The
document.querySelector()
and
document.querySelectorAll()
methods are used to select elements in the DOM. The
querySelector()
method returns the first matching element while
querySelectorAll()
returns a list of all matching elements.
const myDiv = document.querySelector('div');
const dummyDivs = document.querySelectorAll('.dummy');

Styling Elements using JavaScript

You can use JavaScript to style elements in the DOM. To do this, you can use the
style
property of an element.
myDiv.style.color = 'green';

Classes and IDs in CSS

Classes and IDs are used to give specific elements a name that can be used to style them in CSS. To select an element with a specific class, use a dot followed by the class name. To select an element with a specific ID, use a pound sign followed by the ID name.

.dummy {
  color: purple;
}

#test {
  background-color: teal;
}

Traversing the DOM

You can traverse the DOM to select parent or child elements. To select the parent of an element, you can use the
parentNode
property. To select the children of an element, you can use the
childNodes
property.
const testDiv = document.getElementById('test');
const childNodes = testDiv.childNodes;
const parentDiv = testDiv.parentNode;
You can also use the
querySelector()
and
querySelectorAll()
methods to select child elements of a parent element.
const dummyDivs = document.querySelectorAll('.dummy');
const spanElements = dummyDivs[0].querySelectorAll('span');

Getting the ID of an element

We can get the ID of an element using the
id
property:
const id = element.id; // gets the ID of the 'footer' element
console.log(id); // outputs 'footer'
We can even change the ID of an element by assigning a new value to the
id
property:
element.id = 'new-footer'; // changes the ID of the 'footer' element to 'new-footer'

Changing and manipulating ID and class names of HTML elements

We can also change HTML elements' ID and class names using JavaScript. Here's an example:

HTML:
<div id="my-div" class="blue"></div>

Javascript:
const div = document.getElementById('my-div');

// Change the ID
div.id = 'new-id';

// Add a class
div.classList.add('red');

// Remove a class
div.classList.remove('blue');

// Toggle a class
div.classList.toggle('green');
In the example above, we changed the ID of the
div
element from
my-div
to
new-id
. We also added a new class
red
to the
div
element, removed the old class
blue
, and toggled the class
green
(if it was present, it was removed; if it was not present, it was added).

Adding and removing classes to HTML elements

We can add and remove classes to HTML elements using the
classList
property. Here's an example:
HTML:
<div class="my-div"></div>

Javascript:
const div = document.querySelector('.my-div');

// Add a class
div.classList.add('red');

// Remove a class
div.classList.remove('my-div');
In the example above, we added a new class
red
to the
div
element and removed the old class
my-div
. Note that we can also use the
toggle
method to add or remove a class depending on its current state:
div.classList.toggle('green');

If the class 'green' is present, it will be removed; if it is not present, it will be added.

Creating DOM elements

With JavaScript, we can create new DOM elements on the fly. To create a new element, we use the
document.createElement()
method, passing in the tag name of the element we want to create.
const newElement = document.createElement('p');
This will create a new
p
element. You can replace
p
with any valid HTML tag name.
To add text to the element, we can set the
innerText
property of the new element:
newElement.innerText = 'I was created by science.';

Appending elements to an existing element

Once we have created a new element, we can append it to an existing element. To do this, we first need to get a reference to the existing element using its ID. We can then use the
appendChild()
method to append the new element as a child of the existing element.
const creationDiv = document.getElementById('created');
const newElement = document.createElement('p');
newElement.innerText = 'I was created by science.';
creationDiv.appendChild(newElement);
This will append the new
p
element as a child of the
div
with ID "created". You can replace "created" with any valid ID.

Removing elements from the DOM

To remove an element from the DOM, we can use the
removeChild()
method on the parent element, passing in the child element we want to remove.
const creationDiv = document.getElementById('created');
const newElement = document.createElement('p');
newElement.innerText = 'I was created by science.';
creationDiv.appendChild(newElement);
creationDiv.removeChild(newElement);
This will append the new
p
element as a child of the
div
with ID "created", and then remove it immediately.

Putting it all together

Here is an example that puts everything together. We will create a new
ul
element and append several
li
elements to it based on an array of data. We will also remove one of the
li
elements based on its content.
const creationDiv = document.getElementById('created');

// Create a new UL element
const newUL = document.createElement('ul');

// Array of data to create LI elements from
const myFavIceCreams = ['vanilla', 'rocky road', 'strawberry', 'chocolate'];

// Create an LI element for each item in the array
for (let i = 0; i < myFavIceCreams.length; i++) {
  const newLI = document.createElement('li');
  newLI.innerText = myFavIceCreams[i];
  newUL.appendChild(newLI);
}

// Append the new UL element to the creationDiv
creationDiv.appendChild(newUL);

// Find and remove the LI element with innerText of "chocolate"
const childNodes = newUL.childNodes;
for (let i = 0; i < childNodes.length; i++) {
  const childNode = childNodes[i];
  if (childNode.innerText === 'chocolate') {
    newUL.removeChild(childNode);
  }
}
This will create a new
ul
element and append several
li
elements to it based on the
myFavIceCreams
array. It will then find and remove the
li
element with innerText of "chocolate".