About DOM (Document object model) in HTML

sakethkowtha

sakethk

Posted on June 8, 2021

About DOM (Document object model) in HTML

What is DOM ?

DOM (Document object model) is the tree structured data representation of the objects that comprise the structure and content of a document on the web page.

Who will create this DOM ?

Browser's will generate DOM from HTML.

Here is a simple example
Dom tree example

Why do we need DOM ?

We can't manipulate HTML directly. There is a way to manipulate i.e extracting the entire HTML of the page, modifying it and replacing the entire HTML document. But this is very complicated and expensive w.r.t performance. So using DOM we can manipulate styles, content and attributes quickly with the help of javascript.

We can see DOM object in browser inspector. This is how it look like

Dom In Browser

How to manipulate DOM ?

Using javascript api's we can manipulate DOM object. Some of them are

  • createElement
  • appendChild
  • removeElement
  • querySelector
  • querySelectorAll
  • insertBefore
  • addEventListener
  • removeEventListener
  • removeChild
  • replaceChild
  • cloneNode
  • setAttribute
  • getAttribute
  • removeAttribute

Here are some DOM manipulation api examples

   const btn = document.createElement("button");
   const onClick = () => alert("clicked");
   btn.textContent = "Creating Node";
   document.body.appendChild(btn);
   btn.addEventListener("click", onClick);
   btn.setAttribute("disabled", true);
   btn.removeEventListener("click", onClick);
   document.body.removeChild(btn);
Enter fullscreen mode Exit fullscreen mode

Try in Codesandbox

Hope you enjoyed

💖 💪 🙅 🚩
sakethkowtha
sakethk

Posted on June 8, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related