HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

The HTML DOM Document Object

The document object represents your web page. If you want to access any element in an HTML page, you always start with accessing the document object. It is the root owner of all other objects in your page.


Finding HTML Elements

These methods are used to locate elements within the document:

  • document.getElementById(id)
  • document.getElementsByTagName(name)
  • document.getElementsByClassName(name)
  • document.querySelector(CSS selector)

Changing HTML Elements

Once you have found an element, you can modify its properties:

  • element.innerHTML = new content: Changes the inner HTML.
  • element.attribute = new value: Changes attribute values (e.g., src, href).
  • element.style.property = new style: Changes the CSS styles directly.
  • element.setAttribute(attr, val): A specific method to change any attribute.

Adding and Deleting Elements

You can create new elements or remove existing ones using these document-level methods:

  • document.createElement(el): Creates a new HTML element node.
  • document.removeChild(el): Removes an HTML element node.
  • document.appendChild(el): Adds an HTML element as a child.
  • document.replaceChild(new, old): Replaces an HTML element.

Finding HTML Objects

The document object also contains collections of specific objects in the page:

  • document.images: Returns all <img> elements.
  • document.links: Returns all <a> elements with an href attribute.
  • document.forms: Returns all <form> elements.
  • document.title: Gets or sets the title of the document.
Warning: document.write() should only be used for testing. If used after an HTML document has fully loaded, it will overwrite the entire page!

Key Points to Remember

  • Everything in the web page is part of the document object
  • It is the gateway to finding and modifying elements
  • You can create elements "in the air" before attaching them to the page
  • Attribute values can be accessed and changed as object properties
  • Use the style object to modify CSS via JavaScript
  • Always avoid document.write() in production code