JAVASCRIPT Tutorial

Document Object

Key Concepts:

  • Document object: Represents the entire HTML document, including the contents of the <html> tag.
  • document.body: Represents the content of the <body> tag.
  • document.head: Represents the content of the <head> tag.
  • document.getElementById(id): Selects the first element with the specified ID.
  • document.querySelector(selector): Selects the first element matching the specified CSS selector.
  • document.querySelectorAll(selector): Selects all elements matching the specified CSS selector.

Practical Steps:

  1. In the JavaScript console or code editor, type document. This returns the document object.
  2. To access the document's content, use document.body for the body and document.head for the head.
  3. To select elements by ID, use document.getElementById(id).
  4. To select elements by CSS selector, use document.querySelector(selector) for the first matching element and document.querySelectorAll(selector) for all matching elements.

JavaScript Example:

// Get a reference to the document object
const doc = document;

// Explore its properties and methods
console.log(doc.title); // Outputs the document's title
console.log(doc.body.innerHTML); // Outputs the HTML content of the body

// Select elements by ID
const elementById = doc.getElementById("element-id");

// Select elements by CSS selector
const elementsByClass = doc.querySelectorAll(".element-class");

// Perform operations on selected elements
elementById.style.color = "red"; // Changes the element's text color to red