DEV Community

Cover image for DOM in JavaScript
Harini
Harini

Posted on

DOM in JavaScript

What is DOM?

  • DOM stands for Document Object Model.

  • DOM is a programming interface that represents your HTML page as a tree of objects, so that JavaScript can read, add, or delete HTML elements and CSS styles dynamically.

Dom connects HTML+CSS+JavaScript

  • Without DOM, JavaScript cannot control the webpage.

What is HTML DOM?

  • The HTML DOM is a standard object model and programming interface for HTML.

  • It defines:
    1)The HTML elements or tags as objects.
    2)The properties of all HTML elements.
    3)The methods to access all HTML elements.
    4)The events for all HTML documents.

Why we should use DOM?

  • Can change all the HTML elements in the page.

  • Can change all the attributes in the page.

  • Can change all the CSS styles in the page.

  • Can remove existing HTML elements and attributes.

  • Can add new HTML elements and attributes.

  • Can react to all existing HTML elements in the page.

  • Can create new HTML events in the page and so on.

Accessing DOM elements

1)getElementById

<h1 id="title">Hello</h1>

<script>
const el = document.getElementById("title");
console.log(el);
</script>

Enter fullscreen mode Exit fullscreen mode
  • Returns single element

2)getElementsByClassName

<p class="text">One</p>
<p class="text">Two</p>

<script>
const els = document.getElementsByClassName("text");
console.log(els[0]);
</script>
Enter fullscreen mode Exit fullscreen mode
  • Returns HTMLCollection

3)getElementsByTagName

<script>
const els = document.getElementsByTagName("p");
console.log(els[1]);
</script>
Enter fullscreen mode Exit fullscreen mode

4)querySelector

<script>
document.querySelector("#title");  // id
document.querySelector(".text");   // class
document.querySelector("p");       // tag
</script>
Enter fullscreen mode Exit fullscreen mode
  • Returns first matching element

5)querySelectorAll

<script>
const els = document.querySelectorAll(".text");
console.log(els[0]);
</script>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)