DOM
June 2, 2026 4 min read

Quick quick guide for the DOM and implementation

HS
HEMANT SINGH
Technical Writer & Educator

Document object model represents the web page or the structure of web page.

 

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p>CAPSCOM TECHNOLOGY</p>
</body>
</html>

 

  • <html> is called the root element
  • <html> has two child element <head>, <body>
  • <head> has one child element <title>

Accesing document element

  • <html> document.documentElement
  • <body> document.body
  • <head> document.head

Get all the children of selected element

children

Get first element children

firstElementChild

Get last element children

lastElementChild

Get previous element sibling

previousElementSibling

Get next element sibling

nextElementSibling

Get parent element

parentElement

 

DOM has best properties/methods to access the element when the elements are close to each other, but how to access when they are not close.

Get the element by id

If an element has id attribute, we can get it no matter where it is.

 

<div id="company">CAPSCOM TECHNOLOGY</div>
var companyElement = document.getElementById("company");

Get the element by provindg css selector, it return the first matched element.

Element has name

<h1>CAPSCOM TECHNOLOGY</h1>
var company = document.querySelector("h1");

Element has attribute id

<div id="data"></div>
var data = document.querySelector("#data");

Element has attribute class

<div class="data"></div>
var data = document.querySelector(".data");

What if dom has multiple tags with same name,class and id.

querySelectorAll()

var elements  = document.querySelectorAll("h1");

.closest(css)

Get the closest element in upward direction.

 

Get the text and html of element

  • .innerHTML : get the text with the html tags.
  • .textContent : get the text only.

 

Element Attributes

  1. hasAttribute("attribute_name")
  2. Check element has given attribute or not.
  3. getAttribute("attribute_name")
  4.  Get the value of given attribute.
  5. setAttribute("attribute_name", "value")
  6. Set or create new attribute with given value.
  7. removeAttribute("attribute_name")
  8. Remove the given attribute.

 

Create new element

var h1=document.createElement("h1");
h1.innerHTML="Hello";

 

Insertion methods

  • .append()
  • .prepend()
  • .before()
  • .after()

Working with styles and classes.

Change the style of tag.

element.style.backgroundColor="red";

 

Note: always use camel case.

background-color become backgroundColor

 

Changing class name.

element.className=value : It will replace the whole class value.

 

Sometime there is requirement to change the single class.

There we have object classList which have methods to add/remove and toggle class.

  1. element.classList.add()
  2. element.classList.remove()
  3. element.classList.toggle()