Understanding the Document Object Model

Sep 4, 2024

Lecture Notes: Chapter 6 - DOM (Document Object Model)

Introduction

  • Full JavaScript series includes concepts and practical questions with projects to apply them.
  • Chapter 6 focuses on an important concept: DOM (Document Object Model).
  • Topics to cover:
    • What is DOM?
    • How to use DOM?
    • How is DOM generated?

Understanding DOM

  • DOM: A programming interface for web documents.
  • Represents the structure of a document as a tree of objects.

DOM Manipulation

Attributes

  • Elements can have attributes providing additional information.
  • Example:
    • div element can have an id attribute.
    • Accessing attributes through console (e.g., id shows up in the element’s details).

Accessing Attributes

  • Getting an attribute value:
    • Use getAttribute method.
    • Example:
      let div = document.querySelector('div');  
      console.log(div.getAttribute('id'));  
      
  • Setting an attribute value:
    • Use setAttribute method.
    • Example:
      div.setAttribute('id', 'newId');  
      

Styling Elements

  • Access and change styles of an element using:
    • element.style.propertyName
  • Example:
    div.style.backgroundColor = 'blue';  
    

Inserting Elements

Creating New Elements

  • Create new elements using document.createElement.
  • Example for creating a button:
    let newButton = document.createElement('button');  
    newButton.innerText = "Click Me";  
    

Appending Elements

  • Appending: Add new elements to existing elements in the DOM.
  • Use:
    • parentElement.append(childElement)
  • Example:
    let div = document.querySelector('div');  
    div.append(newButton);  
    

Removing Elements

  • Remove elements using the remove method.
  • Example:
    let paragraph = document.querySelector('p');  
    paragraph.remove();  
    

Practice Questions

  1. Create a new button element with the text "Click Me" using JavaScript.
  2. Create a paragraph tag in HTML, give it a class, and style it.
  3. Add a new class using JavaScript without overwriting the existing class.
    • Use classList.add('className') to add a new class.

Conclusion

  • Next Chapter: Events
  • Focus on event handling (e.g., button clicks).
  • Keep learning and coding!