DOM in JavaScript

Hi everyone, welcome back. In this module, I will discuss DOM in JavaScript. In the previous module, I have discussed what events in JavaScript are. After reading this module, you will get to know DOM properties and methods used in JavaScript. Let’s discuss this in detail, without any further delay.

DOM in JavaScript

DOM in JavaScript

The Document Object Model (DOM) is a World Wide Web Consortium (W3C) standard. According to the World Wide Consortium (W3C), everything is a node in the document object model. A document node is the complete HTML document. Each HTML element is an element node, text inside an HTML element is a text node, and the attribute of HTML is an attribute node.

The document object model (DOM) is a hierarchical representation of an HTML document or web page, which is easily interpreted and altered by JavaScript.

Run the below code in your browser console and see the output.

console.log(document);
//or
console.log(window.document);

When the web page or document is loaded in the client’s browser, the whole HTML document is converted into a document object and each HTML element is represented as an object in the DOM. The HTML DOM model is built as a tree-like representation of Objects. Hence, the name is given as the object model.

The entire HTML element or objects are easily accessed and manipulated by JavaScript using different methods and properties with the document object. For example, changing the text and attributes of the HTML tag, changing the styling of the web page such as background color, adding and removing dynamic content to our web page using the document object, and so on. Therefore, DOM is used to add, delete, get and set HTML elements.

Now, let’s see some of the properties of document objects that the document object can access and modify.

What are the properties of document objects?

A property in a document object is a value that can be used to get or set HTML elements or element nodes.

What are the properties of document objects?

Form Object

Form tags in HTML are used to represent it. It includes various form elements like text boxes, checkboxes, radio buttons, buttons, text area, and select.

Link Object

HTML link tags are used to represent it.

Anchor object

The anchor tags in HTML represent anchor objects in DOM.

Now, let’s know document object methods used to target DOM and manipulate the content of the document.

What are document object methods?

A method in a document object is an activity or actions used to access and modify the HTML elements.

write(“string”)

This DOM method is used to print the given message or string on the document.

Syntax
document.write(message);

writeln(“string”)

It is a method used to print the given string on the document terminated with a new line.

Syntax
document.writeln(message);

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
       document.writeln("<h1>This is the writeln() method.</h1>");
       document.write("<h1>This is write() method.</h1>");
</script>
</body>
</html>

getElementById(idName)

It is a method used to access the HTML element by its Id.

Syntax
document.getElementById(Id_Name);

getElementsByClassName(className)

It is a method for accessing an HTML element by its class name.

Syntax
document.getElementsByClassName(Class_Name);

getElementsByTagName(tagName)

This method is used to get the HTML element by the name of the html tag.

Syntax
document.getElementsByTagName(Tag_Name);

getElementsByName(name)

This method is used to return the elements with the given name of the HTML tag.

Syntax
document.getElementsByName(Name);

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Hello, World!</h1>
<h2 id="xyz">This is a JavaScript Tutorial.</h2>
<h3 class="abc">This is a DOM Tutorial.</h3>
<h4 name="pqr">DOM methods.</h4>
<script>
      let a=document.getElementById('xyz');
      let b=document.getElementsByTagName('h1');
      let c=document.getElementsByClassName('abc')[0];
      let d=document.getElementsByName('pqr');

      console.log(a);
      console.log(b);
      console.log(c);
     console.log(d);
</script>
</body>
</html>

What are Get and Set Methods in DOM?

The get method in DOM is used to retrieve the HTML tag as well as their attributes and text whereas the DOM set method is used to set attributes and content of HTML tags.

value

This property is used to get the value of form elements like input fields, checkboxes, radio buttons, etc.

innerText

This property is used to get and set the text of the HTML element or tag. It ignores the spaces. We cannot insert HTML tags while using it, otherwise, it will be printed as plain text.

innerHTML

This property is used to print HTML tags along with the text inside them and is also used to set the content of HTML elements. It also includes the spaces. We can also insert HTML tags.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
  <h1>JS Tutorials</h1>
  <h2 id="abc">Document Object Model</h2>
  <p class="xyz">DOM properties</p>
  <p class="pqr">DOM method</p>
  <input type='text' id="user"/><br/>
  <button type="button" onclick="fun()">Submit</button>
  <script>
    function fun()
    {
      // getting the value from the input field.
      let val=document.getElementById('user').value;
      let h2=document.getElementById('abc');

      // getting and updating the innertext of h2 element.
      console.log(h2.innerText);
      h2.innerText='Welcome,'+val;

      // difference between innerHTML and innerText
      console.log(document.body.innerHTML);
      console.log(document.body.innerText);

      let para=document.getElementsByClassName('xyz')[0];
      para.innerHTML="<h2>DOM PROPERTIES</h2>";

      let para2=document.getElementsByClassName('pqr')[0];
      para2.innerText="<h2>DOM METHOD</h2>";
   }
</script>
</body>
</html>

getAttribute()

The getAttribute() method returns the value of the given attribute of an element.

Syntax
element.getAttribute(attributeName);

setAttribute()

This method is used to set the attribute of an element. It takes two parameters.

Syntax
Element.setAttribute(attributeName, value);

removeAttribute()

This method is used to remove the given attribute of an element.

Syntax
Element.removeAttribute(attributeName);

getAttributeNode()

The getAttributeNode() method returns the given attribute name of an element along with its value.

Syntax
element.getAttributeNode(attributeName);

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
   <h1 style="color: blue;" class="abc" id="xyz">Document Object</h1>
   <h2 id="abc">DOM Methods</h2>
   <button type="button" onclick="get()">Get Attribute</button>
   <button type="button" onclick="set()">Set Attribute</button>
   <button type="button" onclick="remove()">Remove Attribute</button>
   <button type="button" onclick="getAttrNode(this)" class="btn">Get Attribute Node</button>
   <script>
      let a=document.getElementById('xyz');
      let b=document.getElementById('abc');

      function get()
      {
        console.log('id:',a.getAttribute('id'));
        console.log('style:',a.getAttribute('style'));
        console.log('class:',a.getAttribute('class'));
      }
    function set()
    {
      b.setAttribute('class','pqr');
      b.setAttribute('style','color:red; padding:1rem;');
      console.log('style:',b.getAttribute('style'));
      console.log('class:',b.getAttribute('class'));
    }
    function remove()
    {
      b.removeAttribute('class');
      b.removeAttribute('style');
      console.log('style:',b.getAttribute('style'));
      console.log('class:',b.getAttribute('class'));
    }
    function getAttrNode(event)
    {
      console.log('type:',event.getAttribute('type'));
      console.log('class:',event.getAttribute('class'));
      console.log('onclick:',event.getAttribute('onclick'));
    }
</script>
</body>
</html>

What are DOM styling methods?

DOM styling methods are used to get and change the styling of web pages using JavaScript. There are 3 types of methods:

  1. Style
  2. className
  3. classList

Using style

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
<style>
h1{
font-size: 2rem;
color: blue;
}
</style>
</head>
<body>
   <h1>Document Object Model</h1>
   <button class="btn" onclick="fun()">Click Me</button>
<script>
   let h1=document.getElementsByTagName('h1')[0];
   function fun()
   {
     // get styling of h1 element
     console.log('color:',h1.style.color);
     console.log('font-family:',h1.style.fontFamily);
     console.log('font-size:',h1.style.fontSize);
     console.log('border:',h1.style.border);

     // set style of h1 element
     h1.style.color='white';
     h1.style.border='2px solid white';

     // changing body background color to black
     document.bgColor='black';
   }
</script>

Using className

The className method is used to get and set the class name of HTML elements. It returns the string which is a collection of classes associated with the HTML element.

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
h1{
font-size: 2rem;
color: blue;
}
.xyz{
color: red;
}
.pqr{
background-color: aqua;
}
</style>
</head>
<body>
  <h1 class="abc">Document Object Model</h1>
   <button class="btn" onclick="fun()">Click Me</button>
<script>
   let h1=document.getElementsByTagName('h1')[0];
   function fun()
   {
     // getting the class name of the h1 element.
     console.log(h1.className);

     // setting the class name of h1 element.
     h1.className='xyz pqr';
     console.log(h1.className);
   }
</script>
</body>
</html>

Using classList

The classList method is used to retrieve and set the class name of HTML elements and returns an array of classes associated with the HTML element. It also has many methods to add or remove classes.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
h1 {
font-size: 2rem;
color: blue;
}
.xyz {
color: red;
}
.pqr {
background-color: aqua;
}
</style>
</head>
<body>
   <h1 class="abc">Document Object Model</h1>
   <button class="btn" onclick="add()">Add</button>
   <button class="btn" onclick="remove()">Remove</button>
   <button class="btn" onclick="toggle()">Toggle</button>
<script>
   let h1=document.getElementsByTagName('h1')[0];
   function add()
   {
     // getting the class name of the h1 element.
     console.log(h1.classList);

     // setting the class name of the h1 element.
     h1.classList.add('xyz','pqr');

     console.log(h1.classList);
   }
   function remove()
   {
     // removing the class name of the h1 element.
     h1.classList.remove('xyz');

     console.log(h1.classList);
   }
   function toggle()
   {
      // toggle the class name of the h1 element.
      h1.classList.toggle('xyz');

      console.log(h1.classList);
    }
</script>
</body>
</html>

How to set dom.allow_scripts_to_close_windows to true using Javascript?

If your want to close current window or tab using JavaScript, you can do so by executing the following code:

window.top.close();
//Or
window.close();

The above JavaScript code will not directly close Mozilla’s window; you have to enable dom.allow_scripts_to_close_windows and switch it to true to close the current window. You can perform this by following the procedures listed below:

  1. In the browser’s address box, type about:config. A warning message will be displayed and you have to click on accept the risk to continue.How to set dom.allow_scripts_to_close_windows to true using Javascript?
  2. You have to type the following code in the search bar “dom.allow_scripts_to_close_windows” and set it to true.
  3. Now, when you execute the close() method in Mozilla, the window or tab will be closed.

I hope this module will be helpful for you to understand what DOM in JavaScript is, its properties, and its methods. You should try to implement the DOM manipulation using methods and properties of DOM by yourself to gain a better understanding. The DOM has many methods and properties that cannot discuss them in a single article. Keep Coding!