blog bg

November 27, 2023

JavaScript: DOM and Events Fundamentals

Share what you learn in this blog to prepare for your interview, create your forever-free profile now, and explore how to monetize your valuable knowledge.

What is the DOM and DOM manipulation?

DOM stands for Document Object Model and it's a structured representation of HTML documents. The DOM allows us to use JavaScript to access HTML elements and styles in order to manipulate them. For example, we will be able to change text, HTML attributes and CSS styles from JavaScript. We can also say that DOM is a connection point between the HTML documents and JavaScript code. The DOM is automatically created by the browser as soon as the HTML page loads and it's stored in a tree structure. Let's consider following Html code to illustrate the DOM tree in details.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>A Simple Page</title>
  </head>
  <body>
    <section>
      <p>A paragraph with a <a>link</a></p>
      <p>A second parapgraph</p>
    </section>
    <section>
      <img src="dom.png" alt="the dom" />
    </section>
  </body>
</html>
The following image is what a DOM tree for the given HTML code.


 In this  tree structure , each element in the HTML code, is one element node in DOM tree and we can access and interact with each of these nodes using JavaScript. The DOM tree always starts with the document object, at the top. The document is a special object that we have access to in JavaScript and this object serves as an entry point into the DOM. Then the first child element of the document is usually the <HTML> element, because that's the root element in all HTML documents. Next, HTML has two child elements, which are <head> and <body> and these two elements are adjacent elements so, they are siblings in the DOM tree. As we keep going deeper into the nested HTML structure, we keep adding more and more children to the DOM tree. As you can see that <body> has two more child elements(<section>) and even they have their own child elements. In addition to the element nodes, it also has nodes for all the text itself because the rule is that whatever is in the HTML document also has to be in the DOM. So, the DOM really is a complete representation of the HTML document, so that we can manipulate it in complex ways.

NOTE:- DOM and all the methods and properties that we can use to manipulate the DOM, are not part of JavaScript, but they are part of web APIs. So, the web APIs are libraries that the browser implement and we can access it from our JavaScript code.


 

Selecting DOM Elements

We have several methods to select DOM elements

querySelector

The querySelector() method allows us to select the first element that matches a specified CSS selector(s) in the document. If no matches are found, null is returned. For example,

HTML

<section class="right">
        <p class="message">Start guessing...</p>
</section>

JavaScript

console.log(document.querySelector(".message"));

Output

<p class="message">Start guessing...</p>

 

querySelectorAll

The querySelectorAll() method allows us to select all elements that matches a specified CSS selector(s) in the document. For example,

HTML

<section>
  <button class="show-modal">Show modal 1</button>
  <button class="show-modal">Show modal 2</button>
  <button class="show-modal">Show modal 3</button>
</section>

JavaScript

const btnsShowModal = document.querySelectorAll('.show-modal');
console.log(btnsShowModal);

Output

As you can see that, we get a Node list, like an array and it contains all of these three buttons. So, we can simply loop through them to do something with them. For example,
for(let i = 0; i < btnsShowModal.length; i++){
  console.log(btnsShowModal[i].textContent);
}

//output
Show modal 1
Show modal 2
Show modal 3


 getElementById

The getElementById() method allows us to select an element by it's ID and returns null if no matching element was found in the document. For example,

HTML

<body>
    <button id="show-model-btn" class="show-modal">Show modal</button>
    <script src="script.js"></script>
</body>

JavaScript

const showBtn = document.getElementById('show-model-btn');
console.log(showBtn);

Output

<button id="show-model-btn" class="show-modal">Show modal 1</button>


 getElementsByClassName

The getElementsByClassName() method allows us to select elements by their class name. It returns an HTML collection of an array-like object of all elements in the document with the specified class name. For example,

HTML

<body>
  <button class="show-modal">Show modal 1</button>
  <button class="show-modal">Show modal 2</button>
  <button class="show-modal">Show modal 3</button>

  <script src="script.js"></script>
</body>

JavaScript

const showBtns = document.getElementsByClassName('show-modal');
console.log(showBtns);

Output

getElementsByTagName

The getElementsByTagName() method returns an HTML collection of elements with the given tag name. For example,

HTML

<body>
  <button class="show-modal">Show modal 1</button>
  <button class="show-modal">Show modal 2</button>
  <button class="show-modal">Show modal 3</button>

  <div class="modal hidden">
    <button class="close-modal">&times;</button>
  </div>

  <script src="script.js"></script>
</body>

JavaScript

const btnList = document.getElementsByTagName('button');
console.log(btnList);

Output


 
NOTE:- HTML collection is different from NODE list because an HTML collection is also called live collection, meaning that, if the DOM changes then this collection is also immediately updated automatically


 

Reading the Selected DOM Elements

Reading the Text Content

the .textContent property allows us to get the text content of the DOM element. For example,

HTML

<section class="right">
        <p class="message">Start guessing...</p>
</section>

JavaScript

console.log(document.querySelector(".message").textContent);

Output

Start guessing...

 

Reading the HTML content 

the .innerHHML property allows us to get the HTML content of the DOM element. For example,

HTML

<section>
  <h2>Heading Two</h2>
  <p>Paragraph One</p>
  <div>
    <p>Paragraph Two</p>
    <p>Paragraph Three</p>
  </div>
</section>

JavaScript

const section = document.querySelector('section'); console.log(section.innerHTML);

Output


 Reading the value from Input Text

The .value property allows us to get the value of the a text field. For example,

HTML

<section class="left">
  <input type="number" class="guess" value="10" />
</section>

JavaScript

console.log(document.querySelector(".guess").value);

Output

10

Keep in mind that, whenever we get some from the user interface, for example, from an input field, it always is a string.

 

Manipulating DOM elements

Once we have selected DOM elements, we can manipulate them using different methods.

 

Changing the Text Content

the .textContent property allows us to set the text content of the DOM element. For example,

HTML

<section class="right">
        <p class="message">Start guessing...</p>
</section>

JavaScript

document.querySelector(".message").textContent = 10;
console.log(document.querySelector(".message"));

Output

<p class="message">10</p>


 

Changing from the value from Input Text

The .value property allows us to set the value of the a text field. For example,

HTML

<section class="left">
  <input type="number" class="guess" value="10" />
</section>

JavaScript

document.querySelector(".guess").value = 100
console.log(document.querySelector(".guess").value);

Output

100

 

Changing the HTML Content

The .innerHTML property allows us to set the HTML content of a DOM element. For example,

HTML

<body>
  <p>This is a sample Text</p>

  <script src="script.js"></script>
</body>

JavaScript

const pEl = document.querySelector('p');
pEl.innerHTML = "<p>This is new Content</p>";

console.log(pEl);

Output

 

Changing the CSS style

The .style property allows us to get or set the inline style of a DOM element. To do that, first we need to select the element and then apply style on the element. With the style property, we will specify the CSS property in camel case. For example, change the background color of the page.

HTML

<body>
  <header>
  </header>
  <main>
    <section class="left">
    </section>
    <section class="right">
    </section>
  </main>
</body>

JavaScript

const body = document.querySelector('body');
body.style.backgroundColor = "green"

console.log(document.querySelector('body'));

Output

<body style="background-color: green;">
   ...
</body>

Whenever we are manipulating a Style, we always need to specify a string, otherwise it wouldn't work.


 

Adding, Removing and Toggling Classes

The .classList property allows us to add, remove, toggle CSS classes on  a DOM element. For example

HTML

  <body>
    <button class="show-modal">Show modal 1</button>
    <button class="show-modal">Show modal 2</button>
    <button class="show-modal">Show modal 3</button>

    <div class="modal hidden"></div>
    <div class="overlay hidden"></div>

    <script src="script.js"></script>
  </body>

JavaScript

const modal = document.querySelector('.modal');
const overlay = document.querySelector('.overlay');

const btnsShowModal = document.querySelectorAll('.show-modal');
console.log(btnsShowModal);

for(let i = 0; i < btnsShowModal.length; i++){
  btnsShowModal[i].addEventListener('click', function(){
    modal.classList.remove("hidden");
    modal.classList.add("show");
    overlay.classList.remove("hidden");
    overlay.classList.add("show");
    console.log(document.querySelector('.modal'));
    console.log(document.querySelector('.overlay'));
  })
}

Output

 
As you can see that in modal element, we removed the class "hidden"  and added the class "show" , when one of the button is clicked.

We can also toggle between adding and removing a class name from an element  in JavaScript. For example,

HTML

<body>
  <button class="show-modal">Show modal</button>

  <div class="modal hidden">
  </div>
  <div class="overlay hidden"></div>

  <script src="script.js"></script>
</body>

JavaScript

const modal = document.querySelector('.modal');
const overlay = document.querySelector('.overlay');
const showBtn = document.querySelector('.show-modal');

showBtn.addEventListener('click', function(){
  modal.classList.toggle("show");
  console.log(document.querySelector('.modal'));
});

Output

When we click the Show modal button for the first time, show class will be added to modal element like shown below,

<div class="modal hidden show">...</div>

If we click the Show modal button again, then show class will be removed from the modal element like shown below,

<div class="modal hidden">...</div>


 

Changing the Attribute Value

The setAttribute() method allows us to set the value of an attribute on the specified element. For example, we will change the src attribute of an <img> element

HTML

<body>
  <main>
    <img src="dice-5.png" alt="Playing dice" class="dice" />
    <button class="btn btn--roll">Roll dice</button>
  </main>
  <script src="script.js"></script>
</body>

JavaScript

const btnRoll = document.querySelector('.btn--roll');
const imgEl = document.querySelector('.dice');

console.log('Before changing the src attribute');
console.log(imgEl);

btnRoll.addEventListener('click', function(){
    imgEl.setAttribute('src','dice-2.png');
    console.log('After changing the src attribute');
    console.log(imgEl);
});

Output


 

Handling Events

Add an Event listener to a DOM element

We can use addEventListener() method to add an event listener to a DOM element, for example, a mouse click, a mouse moving, a key press and so on. With an event listener, we can wait for a certain event to happen and then react to it when it happens. In order to listen for events, we first need to select the element where the event should happen and we will call the addEventListener() method on that element. In the addEventListener() method, we need to pass two parameters which are the event type and the event handler function, which contains the code that we want to execute whenever the event happens. So, when the given event happen on the selected element then the event handler function is going to be  called. For example, we will change the input value when the button is clicked.

HTML

<section class="left">
  <input type="number" class="guess" value="10"/>
  <button class="btn check">Check!</button>
</section>

JavaScript

const buttonElement = document.querySelector(".check");
buttonElement.addEventListener("click",function(){
    document.querySelector(".guess").value = 15;
    console.log("New value :"+document.querySelector(".guess").value);
});

Output

New Value : 15


NOTE:- we don't call the event handler function anywhere in the code, we just only define the function and pass it into the addEventListener() function, but JavaScript engine will call the function as soon as the event happens.

Let's see an example to handler the keypress events. For example, perform an event by hitting the escape key on the keyboard.

const handlerFunction = function(e){
  if(e.key === "Escape"){
    console.log("Escape key is pressed");
  }
}

document.addEventListener('keydown', handlerFunction);

 

There are three types of events for the keyboard, which are,

  • key up: This event will only happen when we lift the finger off the key. 
  • key press: This event is fired, when we keep our finger on a certain key and 
  • key down: This event is fired as soon as we just press down the key.

 

Remove an Event listener to a DOM element

We can use the removeEventListener() method to remove an event listener from a DOM element. This method takes the same parameters as the addEventListener() method. Consider following example where wee added a .addEventListener() on header element when there is a  mouse enter event happens,

const header = document.querySelector('header');

header.addEventListener('mouseenter', function(e){
    console.log('You are currely on the Header section');
});

To remove this event listener from the header, we first need to export the function into a named function, After that, we can remove that event listener like shown below,

const header = document.querySelector('header');

const mouseEnterEvent = function(e){
    console.log('You are currely on the Header section');
}

header.addEventListener('mouseenter', mouseEnterEvent);

header.removeEventListener('mouseenter', mouseEnterEvent);

For this reason, we will have to export the function into its own function. Also, we can remove the event listener at any place in our code.

 

Next ArticleJavaScript: Advanced DOM and Events Fundamentals

334 views

Please Login to create a Question