Introduction to DOM and Related APIs

The Document Object Model (DOM) is a W3C standard API for manipulating HTML/XML documents. It provides a structured representation of web documents enabling dynamic content modification through programming interfaces. DOM Tree Structure

  • Document: Represents the entire web page as a root node
  • Element: Corresponds to HTML tags as node objects
  • Node: Encompasses all document components including tags, attributes, text, and comments

The DOM treats all these components as objects in a hierarchical tree structure.

Element Selection Methods

1. ID-based Selection

Use getElementById() to retrieve elements by unique identifier:

document.getElementById('mainContent');

Tip: Use console.dir() to inspect element propertise and methods.

2. Tag Name Selection

Access elements by tag name using getElementsByTagName():

document.getElementsByTagName('div');

Key characteristics:

  • Returns a live HTMLCollection
  • Requires iteration for individual element manipulation
  • Returns empty pseudo-array if no elements match

Example: Get li elements with in a container:

const container = document.getElementById('contentArea');
const items = container.getElementsByTagName('li');

3. Modern Selection APIs

HTML5 introduced enhanced selection methods:

  • getElementsByClassName() - Select by class name
  • querySelector() - Get first matching element
  • querySelectorAll() - Get all matching elements

Usage example:

<body>
  <div class="section">Section 1</div>
  <div class="section">Section 2</div>
  <nav id="menu">
    <ul>
      <li>Home</li>
      <li>About</li>
    </ul>
  </nav>
  <script>
    // Class-based selection
    const sections = document.getElementsByClassName('section');
    
    // Single element selection
    const firstSection = document.querySelector('.section');
    
    // ID-based selection
    const menu = document.querySelector('#menu');
    
    // Multiple element selection
    const allSections = document.querySelectorAll('.section');
    
    // Tag selection
    const navItems = document.querySelectorAll('nav li');
  </script>
</body>

Important: CSS seletcors require proper syntax (e.g., #menu, .section).

4. Special Elements

Direct access to root elements:

// Access body element
const body = document.body;

// Access html element
const html = document.documentElement;

Tags: DOM javascript html Element Selection W3C

Posted on Wed, 24 Jun 2026 17:26:08 +0000 by liquidchild