JavaScript DOM Manipulation Overview

Sep 24, 2024

JavaScript DOM Manipulation Crash Course

Introduction

  • Previous courses: HTML Crash Course, CSS Crash Course.
  • New course focus: JavaScript fundamentals for beginners (not titled "crash course").
  • Key concepts covered: variables, arrays, functions, loops.

Objective of the Video

  • Go beyond basic JavaScript.
  • Focus on DOM manipulation using vanilla JavaScript (as opposed to jQuery).
  • Techniques: selecting items, changing styles, replacing content.

What is the DOM?

  • Stands for Document Object Model.
  • Tree of nodes/elements created by the browser from HTML.
  • JavaScript can manipulate the DOM (add, change, remove elements).
  • Object-oriented structure with properties and methods.

Browser and Document Objects

  • Window object: represents the browser.
  • Document object: core of the DOM, contains all elements.
  • Root element: HTML tag.
  • Children: head and body elements, each with their own children (e.g., title, H1).

Setting Up the Project

  • Simple HTML page created with Bootstrap for styling.
  • Key elements: header, card with a form, list group.
  • Code structure: link to Bootstrap CDN and empty JavaScript file (dom.js).
  • Live Server for auto-reloading on changes.

Exploring the Document Object

  • Using console.dir(document) to inspect properties and methods of the document object.
  • Important properties:
    • document.domain, document.url, document.title, document.head, document.body, document.all.

Selecting Elements

  1. getElementById

    • Example: document.getElementById('headerTitle') to select an element by its ID.
  2. getElementsByClassName

    • Returns an HTML collection of elements with that class.
    • Example: document.getElementsByClassName('list-group-item').
    • Requires looping to change styles on all items.
  3. getElementsByTagName

    • Similar to class name but selects by tag.
    • Example: document.getElementsByTagName('li').
  4. querySelector

    • Selects the first matching element using CSS selectors.
    • Example: document.querySelector('.header') selects the header.
  5. querySelectorAll

    • Similar to querySelector but selects all matching elements.
    • Returns a NodeList (can use array methods).
    • Example: document.querySelectorAll('.title').

Manipulating Elements

  • Changing text:
    • Use textContent, innerText, innerHTML to adjust text within elements.
  • Changing styles:
    • Example: element.style.property = 'value';
    • Use camelCase for CSS properties.
  • Using looping to apply styles/effects to collections of elements.

Next Steps

  • Future videos will cover:
    • Traversing the DOM (parents, children).
    • Events (mouse and keyboard events).
    • More advanced DOM manipulation techniques.

Conclusion

  • This is a foundational course for understanding and manipulating the DOM with vanilla JavaScript.