Manipulating The DOM Pt.1: #100DaysOfCode Day 2

Manipulating The DOM Pt.1: #100DaysOfCode Day 2

·

2 min read

Welcome to day 2 of my #100DaysOfCode blogging journey!

In today's blog we will be delving into the Document Object Model (DOM) and its manipulation using JavaScript. The DOM methods are not only exclusive to JavaScript, but are also part of the browser's Web API.

To get started with DOM manipulation, we can use the following code snippet:

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

This code retrieves the text content of the HTML element with the class "message" and logs it to the console.

However, this merely retrieves and prints an existing value. We can dynamically change the value of an element by setting its text content to a new value. For instance, we can change the text content of an element with the class "message" to "Correct Number" using the following code:

document.querySelector('.message').textContent = 'Correct Number';

The DOM breaks down an HTML document into a tree-like structure, with parent and child elements. The above code changes the text content of the child element with the class "message".

To create dynamic changes to an element, such as through user input, we can use the addEventListener method. This method allows us to wait for an event to occur and then respond to that event accordingly. For example, we can create a number guessing game where a user inputs a number and then checks to see if it matches the correct number.

Here is an example code block that accomplishes this:

document.querySelector('.check').addEventListener('click', function () {
  const guess = Number(document.querySelector('.guess').value);
  console.log(guess, typeof guess);
});

In the above code, we add an event listener that listens for the 'click' event on the element with the class "check". When this event occurs, the function provided as the second argument to addEventListener is executed.

Inside the function, we retrieve the value of the input element with the class "guess" and convert it to a number using the Number constructor. This allows us to compare the input value to the correct number. We then log the value and type of the guess to the console for debugging purposes.

In summary, DOM manipulation with JavaScript allows us to create dynamic changes to HTML elements based on user input and other events. The addEventListener method is a powerful tool that allows us to respond to these events in real time.

Thanks for stopping by for Day 2 of this documented journey! I have been learning and putting my knowledge to work since October 2021. It's nice to make something official that shows my understanding of the topic.