HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript HTML DOM Methods

HTML DOM methods are actions you can perform (on HTML Elements). HTML DOM properties are values (of HTML Elements) that you can set or change.


The innerHTML Property

The easiest way to get or modify the content of an HTML element is by using the innerHTML property. It allows you to read or write the content inside an element using HTML strings.

document.getElementById("p1").innerHTML = "New text!";

Finding HTML Elements

Before you can change an element, you must find it. There are several ways to do this:

  • getElementById("id"): Finds an element by element id.
  • getElementsByTagName("tag"): Finds elements by tag name.
  • getElementsByClassName("class"): Finds elements by class name.
  • querySelector("selector"): Finds the first element that matches a CSS selector.
  • querySelectorAll("selector"): Finds all elements that match a CSS selector.

Example: Selection in Action

// Find element with ID "main"
const element = document.getElementById("main");

// Find all 

elements const paragraphs = document.getElementsByTagName("p"); // Find all elements with class "intro" const intros = document.getElementsByClassName("intro");

Best Practice: Use querySelector() and querySelectorAll() for most cases. They are more flexible because they accept any valid CSS selector (ids, classes, tags, and nested selections).

Key Points to Remember

  • Methods are actions; Properties are values
  • innerHTML is the primary tool for content updates
  • getElementById is the fastest way to find a single element
  • Use querySelector for modern, complex selections
  • The document object provides all these core methods
  • Selection methods return individual elements or collections (lists) of elements