Skip to content

JS DOM

The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects; that way, programming languages can interact with the page.

A web page is a document that can be either displayed in the browser window or as the HTML source. In both cases, it is the same document but the Document Object Model representation allows it to be manipulated. As an object-oriented representation of the web page, it can be modified with a scripting language such as JavaScript.

Here are some of the most common JavaScript methods for interacting with the DOM:

  1. Selecting Elements:

    • getElementById(id) — Selects an element by its id.
    • getElementsByClassName(className) — Selects elements by their class name.
    • getElementsByTagName(tagName) — Selects elements by their tag name (e.g., div, p, etc.).
    • querySelector(selector) — Selects the first element that matches the given CSS selector.
    • querySelectorAll(selector) — Selects all elements that match the given CSS selector.
  2. Manipulating Element Content:

    • innerHTML — Gets or sets the HTML content of an element.
    • innerText or textContent — Gets or sets the text content of an element.
  3. Changing Styles:

    • style — Allows you to manipulate an element’s inline styles.
  4. Creating and Appending Elements:

    • createElement(tagName) — Creates a new HTML element.
    • appendChild(childNode) — Appends a new child element to an existing element.
    • removeChild(childNode) — Removes a child element from an element.
<html>
<body>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color = "blue";
</script>
</body>
</html>