Javascript DOM Manipulation

  • most javascript is interacting with the DOM
    • examples:
      • games
      • scrolling effects
      • dropdown menus
      • form invalidations
      • interactivity
      • animations
      • every awesome site ever :'D

Defining the DOM

  • DOM stands for Document Object Model
  • it is the interface between your Javascript and HTML+CSS
  • special javascript objects, methods, and functions that we can use to interact with our HTML and CSS
    • can add elements, remove things, change colors, animate things, etc, etc
  • the browser turns every HTML tag into a javascript object that we can manipulate
  • creates the document object
  • everything is stored inside of the document object
  • example document object : DOM

Select and Manipulate

  • like CSS where we write a selector, with the DOM we write javascript code that goes and **selects ** objects and then we change properties on them...i.e. we manipulate them
  • example: change the color of an h1 element
    • first select the h1 and same it to a variable --- let h1 = document.querySelector('h1');
    • then manipulate it --- = 'pink';
  • example: select the <body> and change its color every second
    let body = document.querySelector('body');    // SELECT
    let isBlue = false;
    setInterval(function(){                       // MANIPULATE
      if(isBlue){ = 'white';
      } else { = '#3498db';
      isBlue = !isBlue;
    }, 1000);

Important Selector Methods

  • sample HTML used for examples that follow:
          <title>Selectors Info</title>
            <li id="highlight">List Item 1</li>
            <li class="bolded">List Item 2</li>
            <li class="bolded">List Item 3</li>
  • document.getElementById()
    • takes a string argument and returns the first element with a matching ID
    • example: let highlight = document.getElementById('highlight');
    • the return looks like HTML, but it's actually a javascript object
  • document.getElementsByClassName()
    • will return a list of all the elements with the class --- looks like an array, but is actually an array-like item called an HTMLCollection --- like a light array, missing some features of arrays
    • example:let bolded = document.getElementsByClassName('bolded');
  • document.getElementsByTagName()
    • returns a list of all elements of a given tag
    • example:let li = document.getElementsByTagName('li');
  • document.querySelector()
    • returns the first element that matches a given CSS-style selector
    • example: let li = document.querySelector('#highlight');
    • example: let class = document.querySelector('.bolded');
    • example: let h1 = document.querySelector('h1');
    • can use nested CSS tags
  • document.querySelectorAll()
    • the same as querySelector() but returns all matching elements instead of just the first one
    • can still use if there is only one element, it will just be a list of one

Manipulating Style

  • even though we are changing CSS, this is javascript, so there have to be quotes around the values being assigned
  • changes take place immediately

Changing an Element's style

  • example of selecting an element & manipulating it:
    let tag = document.getElementById('highlight'); = 'blue'; = '10 px solid red'; = '70px'; = 'yellow'; = '200px';
    • not very DRY code
  • although they have to interact, it's better to keep the javascript, CSS, and HTML as separate as possible

Adding/Removing Classes

  • if need to make multiple changes, a better way is to create a class with the desired changes in your CSS --- then javascript just adds the class to elements instead of changing all the attributes one by one like in the above example
  • alternative example to the one above using classList:
      color: blue;
      border: 10px solid red;
      fontSize: '70px';
      background: 'yellow';
      marginTop: '200px';
    let tag = document.getElementById('highlight');
  • classList is a read-only list that contains the classes for a given element --- it is not an array
  • methods:
    • .classList.add('className')
    • .classList.delete('className')
    • .classList.toggle('className')
      • if the element has the class name it will remove it
      • if it doesn't have the class name then it will turn it on (add it)

Manipulating Text and Content


  • returns a string of all the text contained in a given element
  • the content is everything between the tags but not including the tags
  • example:
      This is an <strong>awesome</strong> paragraph
    let tag = document.querySelector('p');  // select the <p> tag
    tag.textContent                         // retrieve the textContent                  
    // "This is an awesome paragraph"
    tag.textContent = 'blah blah blah';     // alter the textContent
    tag.textContent                         // retrieve the textContent
    // "blah blah blah"                  
    • could just chain it onto .querySelector
  • will get rid of everything in an element and overwrite it, so you will lose any other tags that were contained within the one you're changing


  • similar to textContent, except it returns a string of all the HTMl contained in a given element
  • example:
      This is an <strong>awesome</strong> paragraph
    let tag = document.querySelector('p');
    // "This is an <strong>awesome</strong> paragraph"
  • don't usually use innerHTML to alter things because it will have the same problem as textContent
  • can assign text with HTML and it will render the HTML
    • document.body.innerHTML = '<strong>HELLO</strong>' will render with the HELLO in bold , while document.body.textContent = '<strong>HELLO</strong>' will render <strong>HELLO </strong>'

Manipulating Attributes

  • use .getAttribute() and .setAttribute to read and write attributes like src and href
  • example:
    <a href="">I am a link</a>
    <img src="logo.png"
    let link = document.querySelector('a');
    link.getAttribute('href');                       // ""
    // change href attribute
    link.setAttribute('href', '');// <a href="">I am a link</a>
    // change the image src
    let img = document.querySelector('img');
    img.setAttribute('src', 'corgi.png');            // <img src="corgi.png">
  • works on any attributes...class, id, etc.

Copyright © 2022