JavaScript DOM Manipulation Cheat Sheet

DOM manipulation can be done using basic JavaScript. When interactive web applications are designed and created, DOM elements must be modified with user interaction. And, DOM manipulation is the process of modifying the document object model, along with its content.

Creating DOM Elements

Create an Element From Scratch With createElement()

This is one of the most widely used operations, where a new DOM element gets created during user interaction. The createElement method can be used to create a new element based on the tag name.

The attribute passed into the createElement method can be in lower or uppercase. The method converts the tag name to lowercase, before creating the new element. 

1
// creating div
2
var element = document.createElement('div');
3

4
// creating paragraph element
5
var element = document.createElement('p');
6

7
// creating image element
8
var element = document.createElement('img');
9

10
// creating anchor element
11
var element = document.createElement('a');

Import an Element With importNode()

You can import a node from another document. For this, importNode method is used.

1
const importedNode = iframe.contentWindow.document.getElementById("myNode");
2

3
// if all the descendants of the imported node have to be copied
4
// deep = true
5
// if all the descendants of the imported node don't have to be copied
6
// deep = false
7
const deep = true
8
const element = document.importNode(importedNode, deep);

Clone an Element With cloneNode()

Likewise, you can clone an existing element, and create a new one.

A drawback in using this method could be duplication of element IDs. Ensure that the id of the newly created element is modified.

1
let p = document.getElementById("paragraph");
2
// if all the descendants of the imported node have to be copied
3
// deep = true
4
// if all the descendants of the imported node don't have to be copied
5
// deep = false
6
const deep = true
7
let duplicateParagraph = p.cloneNode(deep);

Attaching the New Element to the Document

Once the element is created or imported, it will not be attached to the document directly. The newly created element will be stored in a reference, and it would float around aimlessly. This is why another method has to be called, too append the newly created element to the document.

And, there are a few methods to attach an element to the document.








Method Description
append() appends a DOMString object, or a Node object to the parent element
appendChild() appends only Node objects to the parent element
insertBefore() inserts a new element before the parent element
prepend() inserts the new element before all the other child elements in the parent
1
<div id="parent">
2
  <p>Parent</p>
3
</div>
4
<button onclick="addChild()">Add Child</button>
5

6
<script>
7
  function addChild() {
8
    const parent = document.getElementById("parent"); // selecting parent
9
    const child = document.createElement("p"); // creating child
10
    child.innerHTML = "First Child"; // adding some content
11
    
12
    const child2 = document.createElement("p"); // creating child
13
    child2.innerHTML = "Second Child"; // adding some content
14
    
15
    // appending child to parent
16
    parent.append(child);
17
    parent.appendChild(child2);
18
    
19
    const grandparent = document.createElement("p"); // creating ancestor
20
    grandparent.innerHTML = "Grand Parent"; // adding some content
21

22
    // appending before parent
23
    parent.insertBefore(grandparent);
24
  }
25
</script>

Selecting Elements

Before you modify element attributes, you must ensure that the element gets selected correctly. There are many ways to select an element, based on its properties. Let’s walk through few useful, and commonly used methods for selecting elements.

Query Methods

The query methods let you use a CSS selector to find elements in your document.

querySelector(selector)

Returns the first element to match a specified selector. If there are no matching elements, null is returned. 

querySelectorAll(selector)

Returns all elements that meet the selector, null if there are no matching elements.

1
const element = document.querySelector(selectors)
2
const element = document.querySelectorAll(selectors)

The selectors should be a valid CSS selector string. Example selectors are given below:

  • #main: the element with the id main
  • .login: elements with the class name login
  • form.login input[type="button"]: all button inputs within a form with class name login

Getter Methods

getElementById(id)

Returns an element with the given ID. For this method to work efficiently, you must provide unique element IDs. If there are no matching elements, the method returns null.

getElementByClassName(classname)

Returns all elements with the given class name. If multiple class names are mentioned, only elements with all the class names will be returned. Elements returned will be a part of the live HTMLCollection. If code modifies a class name—the outcome of this method will be affected. This is why care needs to be taken while using this method inside an iteration.

getElementsByTagName(tagname)

Returns all elements with a given tag name. This method searches through the entire root node. Elements returned by this method are a part of the live HTMLCollection. Removing and adding elements to the DOM tree will automatically modify the result of this method.

1
  <body>
2
    <p id="para" class="test_class">Some text here</p>
3
    .
4
    .
5
  </body>
6
  
7
  const elem = document.getElementById("para");
8
  const element_by_classname = document.getElementsByClassName("test_class");
9
  const element_by_tagname = document.getElementsByTagName("p"); 

DOM Tree Traversal

We can also traverse a DOM tree, using a node’s child and sibling elements. 












Method Description
parentNode() returns the parent node of an element
parentElement() returns the parent element of an element, without it’s text and comment nodes
childNodes() returns all the child nodes of an element
firstChild() returns the first child of an element
lastChild() returns the last child of an element
children() returns a collection of child elements without text, and comment nodes
previousSibling() returns the previous sibling node of an element
nextSibling() returns the next sibling node of an element
1
<div id='parent'>
2
    <p id='first_child'>First Child</p>
3
    <p id='middle_child'>Middle Child</p>
4
    <p id='last_child'>Last Child</p>
5
</div>
6

7
const middle_child = document.getElementById('middle_child')
8

9
const parent = middle_child.parentNode() //parent
10
parent.lastChild() //last_child
11
parent.firstChild() //first_child
12
middle_child.previousSibling() //first_child
13
middle_child.nextSibling() //last_child
14
parent.children() // ['first_child', 'middle_child', 'last_child']

DOM Events

Interactivity of JavaScript comes from the DOM event listeners. The event listeners are called whenever there is a mouse movement, or key stroke. The listeners have to be connected to a node or element. This is why the method is called an ‘event listener’. The method listens if an event occurred or not.

Information about the event are held inside an object, called the event object. When an event listener is called, the event object tracks the target, event type and all associated properties. 

There are several different types of events:

  • Keyboard Events: these capture a user’s interaction with the keyboard. Details of the key pressed are stored in the key property. The keyboard events are fired in stages: keyDown, keyUp and keyPress. keyPress is fired only when there is a character involved, and not a modifier. (Modifiers are keys like tab, and caps lock on).
  • JavaScript Events: these can be used to manipulate the DOM. The goal of these events is to make the page as dynamic as possible. Whenever the user scrolls, clicks a button or performs an action – these events will be fired. Functions registered to events like onScroll, onClick, onFocus and onLoad are called event handlers.
  • Mouse Events: these can be used to capture a user’s interaction with the mouse. Events are fired on click, mouseUp, mouseDown, mouseOver and mouseOut

.addEventListener(eventType, handlerFunction)

The addEventListener method is the recommended solution for registering DOM events. 

  • It allows users to add multiple event handlers for a single event.
  • It helps users to control when an event can be activated, or removed. 
  • It works on all event target types, ranging from SVG elements to traditional HTML content.
1
document.addEventListener("click", (event) => console.log(event))

.removeEventListener(eventType, handlerFunction)

As mentioned above, we have the freedom to activate and deactivate event listeners from anywhere in the code. The removeEventListener method is used to stop the document from listening to events. Just like the addEventListener function, we need to pass two arguments into the removeEventListener method.

1
eventTarget.addEventListener("event", eventHandlerFunction);
2

3
eventTarget.removeEventListener("event", eventHandlerFunction);

Remove DOM Elements

Remove Child Elements With removeChild()

Just like creation, elements may need to be removed from the document too. For this, the removeChild method can be used. The removeChild method returns the deleted node’s reference. The removeChild method has to be called from its parent or else, an error will be thrown.

1
// selecting parent and child
2
const parent = document.getElementById("parent");
3
const child = document.getElementById("child");
4

5
// removing child from parent
6
parent.removeChild(child);

Replacing Elements with replaceChild()

Another method for removing DOM elements, is replacing them with newer child elements. 

1
// selecting parent
2
const parent = document.getElementById("parent");
3
// selecting oldElement
4
const oldElement = document.getElementById("child");
5
// creating newElement which is newChild
6
const newElement = document.createElement("newChild");
7

8
function replace() {
9
  newElement.innerHTML = "This is a new child"
10
  parent.replaceChild(newElement, oldElement);
11
}

Conclusion

We have come to the end of our JavaScript DOM manipulation cheatsheet. These are essential methods when you want to make dynamic changes in the DOM.


Source link