2023-05-16 DOM Manipulation

main topics

main takeaways

What's the DOM

Trying to explain with my words:

DOM Manipulation

In my understanding DOM manipulation usually boils down to these 3 steps:

  1. select an element
  2. define a function you want to execute
  3. define which event, happening in the element, should trigger the function.

Such steps are usually performed using these techniques:

  1. document.querySelector() or .getElementById()
  2. write a function receiving an event as argument
  3. element.addEventListener(event, function)

  • document.querySelector(cssSelector) returns the first element matching the cssSelector.
  • document.querySelectorAll(cssSelector) returns an array with all elements matching the cssSelector

Changing the Style

const element = document.querySelector(CSS_SELECTOR);

// hiding the element
element.style.display = "none"; // Hide
element.style.display = ""; // Show

// change the background
element.style.backgroundColor = "#fce";

The CSS properties are written in kebab-case (words separated by a dash), but in JavaScript they are in camelCase.

Example: background-color = el.style.backgroundColor

Adding / Removing classes


Editing the contents of an element

Edit the text inside an element:

// the contents are always literal
element.innerText = "new text"

// this string is going to be considered as text
element.innerText = "this will <em>NOT</em> be interpreted as an HTML tag"

Edit the HTML inside an element

// the HTML tags here will emphasize the text
element.innerHTML = "I <em>love</em> Ruby"

// creating a link
element.innerHTML = `<a href="${url}">${linkDescription}</a>`

getting value from input fields

<!-- Some HTML -->
<input name="email" id="email" value="paul@gmail.com" />
const emailInput = document.getElementById("email");

console.log(emailInput.value);       // Read

emailInput.value = "john@gmail.com"; // Write

some events

Full list of events: https://developer.mozilla.org/en-US/docs/Web/Events

# most used during the bootcamp
click   # any visible element
submit  # form
keyup   # window / any focused element

# also common
DOMContentLoaded # document
blur             # input / textarea
change           # select
focus            # any visible element
mouseover        # any visible element
resize           # window
scroll           # window / any scrollable element
touchstart       # for mobile devices

avoiding the default behavior


An example of how it's useful is to prevent the reload of the page when a form is submitted.

const input = document.getElementById('input-text');

input.addEvenetListener('submit', (event) => {
  // do something cool...