loading...

javascript: DOM (document object model)

german profile image german9304 ・2 min read

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">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>DOM</title>
  </head>
  <body>
    <div class="container">
      <p id="pragraph">my paragraph</p>
    </div>
    <section>
      <header>
        <h1>header</h1>
      </header>
      <div class="container">
        <p class="counter">0</p>
      </div>
    </section>
  </body>
</html>

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');
console.log(paragraphById);

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 --->
 <script>
 //  here goes your js  
</script>

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

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

Posted on by:

Discussion

markdown guide