Playing With DOM using Javascript

·

2 min read

What do you mean by DOM ?

The Document object model(DOM) is an application programming interface (API) for HTML , The browser parses the content into a tree of Objects Which is Known as DOM, we can access these objects and make changes in the documents structure, style and content using javascript. The browser renders these changes and displays a new page as per the changes made in the DOM.

Note: The changes made using DOM API changes only the DOM tree but not the HTML

Let's See an example HTML document and DOM tree for the document

  <!doctype html>
  <html>
    <head>
       <title>Hello, world!</title>
  </head>
  <body>
      <h1>Hello, world!</h1>
      <p>This is a hypertext document on the World Wide Web.</p>
      <script src="/script.js"></script>
  </body>
  </html>

DOM Tree.png


But ,How can we use HTML elements using javascript ?

We have predefined methods to reference the HTML elements in javascript:

Methods for referencing HTML elements:

document.getElementById("id") finds an element by its id.

document.getElementByClassName("ClassName") finds an element by its class.

document.getElementByTagName("tag") finds an element by its tag.

document.querySelector("") returns the first element which matches the given selector.

document.querySelectorAll("") returns a nodelist of all elements which matches The given selector.

let's see an example

   <h1 id="header">Heading</h1>
   <div class="container">This is a container div</div>
   <p>This is a paragraph</p>
   <p>This is another paragraph</p>

Let's See how we can reference them in the javascript world

 var heading=document.getElementById("id");//This references h1 
 var containerElement=document.document.getElementByClassName("container");
  //This references div
 var paragraph=document.getElementByTagName("p");//This references the first p tag 
 var paragraphList=document.queryselectorAll("p");// This returns a nodelist of p tags

Note: while using document.querySelector("") if you are referencing the element by its id pass the argument as "#id" ,for referencing the element using class name pass the argument as ".className"

id in "#id" refers to the value given in the id attribute of your HTML element and className in ".className" refers to the value given in the class attribute of your HTML element

you can also create a HTML element using document.createElement(element) method.

IF you want to know more about DOM API and their methods please refer:

MDN web Docs

javascript info

w3 schools


Thank you for reading🤝

Let's connect