DEV Community


Posted on

javascript: DOM (document object model)

What is the DOM?

The DOM is a representation of the html elements in your document as a tree.

What does this mean?

It means that this html gets represented as a tree, so you can manipulate it with javascript.

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <div class="container">
      <p id="pragraph">my paragraph</p>
      <div class="container">
        <p class="counter">0</p>

How do I access the DOM through javascript?

Well there are a couple of ways, however you need the global property called document, here is an example:

// By using querySelector or getElementById or getElementsByClassName

// Query selector 
  const paragraph = document.querySelector('#pragraph');
  console.log(paragraph); // this will get the paragraph element. 

// Or get element By id 
const paragraphById = document.getElementById('pragraph');

To access any element we can just call querySelector:

  const div = document.querySelector('div'); // first div
  const divs = document.querySelectorAll('div'); // all divs
 One thing to notice here is that 
 document.querySelectorAll will get all the divs,
 and document.querySelector will get the first div it encounters. 

Also by accessing the DOM with javascript you can manipulate it however you want, for example we can access the counter element and increment it by 1

const counter = document.querySelector('.counter');
counter.textContent = '1';

One import thing to say is that js must be inside the script tag or you can import a file

<!--- no file --->
 //  here goes your js  

<!--- file --->
<script src="./somescriptfile"> </script> 

Thank you and please leave some feedback :) I hope you enjoy the reading.

Top comments (0)