Skip to content

05. DOM and Events

idavidov13 edited this page Jan 26, 2024 · 5 revisions

DOM

Browser Object Model (BOM) - Browsers expose some objects like window, screen, navigator, history, location, document, …

image

Document Object Model (DOM)

The DOM represents the document as nodes and objects. That way, the programming languages can connect to the page.

The HTML DOM is an Object Model for HTML. It defines:

  • HTML elements as objects
  • Properties
  • Methods
  • Events

The browser parses HTML and creates a DOM Tree

The elements are nested in each other and create a hierarchy, like the hierarchy of a street address – Country, City, Street, etc.

DOCUMENT OBJECT MODEL: structured representation of HTML documents. Allows JS to access HTML elements and styles to manipulate them. image

DOM Methods

DOM Methods - actions you can perform on HTML elements

DOM Properties - values of HTML elements that you can set or change

The HTML DOM method is an action you can do (like add or delete an HTML element)

HTML DOM property is a value that you can get or set (changing the content of an HTML element)

Using the DOM API

JavaScript can interact with web pages via the DOM API:

  • Check the contents and structure of elements on the page
  • Modify element style and properties
  • Read user input and react to events
  • Create and remove elements

Most actions are performed when an event occurs

  • Events are "fired" when something of interest happens

All of this and more will be examined in upcoming lessons

JavaScript in the Browser

Code can be executed on the page in different ways:

  • Directly in the developer console – when debugging
  • As a page event handler – e.g., the user clicks on a button
  • Via inline script, using <script> tags
  • By importing from an external file – the most flexible method

Elements and Properties

The DOM Tree is comprised of HTML elements

Elements are JS objects with properties and methods

  • They can be accessed and modified like regular objects

To change the contents of the page:

  • Select an element to obtain a reference
  • Modify its properties

Attributes and Properties

HTML defines attributes

  • Attributes initialize DOM properties
  • Property values can change via the DOM API

The HTML attribute and the DOM property are technically not the same thing

Since the outcome is the same, you will almost never encounter a difference in practice!

DOM Manipulations

The HTML DOM allows JavaScript to change the content of HTML elements

  • innerHTML
  • textContent
  • value
  • style

Targeting Elements

There are a few ways to find a certain HTML element in the DOM:

  • By ID - getElementById()
  • By class name - getElementsByClassName()
  • By tag name - getElementsByTagName()
  • By CSS selector - querySelector(), querySelectorAll()
    These methods return a reference to the element, which can be manipulated with JavaScript

Clone this wiki locally