Rod's log

JavaScript DOM

29/06/2023

What is the DOM?

In simple terms, the DOM is a bunch of little packages that are organised in a way so that a computer can understand what is there. It represents a webpage in objects (little boxes) and programmers can use computer languages to manipulate those objects.

The DOM (Document Object Model) is like a family tree, in which every HTML element is considered a parent, sibling or child element. For example:

        
        <!DOCTYPE html>
        <html>

          <head>
            <title>My Web Page</title>
          </head>

        <body>

          <h1>Welcome to My Web Page</h1>
          <p>This is a paragraph.</p>
          <img src="image.jpg" alt="An image">
          <button>Click Me</button>

        </body>

        </html>
        
      

The <html> tag is the root of the tree, and it has child elements such as <head> and <body>. Then, the <body> element has other child elements like <h1>, <p>, <img>, and <button>. Each of these elements is a “node” in the DOM.

Programmers use JavaScript to manipulate those “nodes” inside the DOM, changing their content, modifying their attributes, adding or removing elements dynamically, and responding to user interaction such as clicks or form submissions.

JavaScript HTML and CSS

What is JavaScript?

JavaScript is a programming language that gives us tools to manipulate the structure and the behaviour of a webpage. It can make the page more dynamic and act the way we want it to behave. For example, we can create a button that changes the size or content of a paragraph. JavaScript also “remembers” things because we can create variables and functions that store information so we can use it as many times as we want.

This button doesn't do anything because there is no JavaScript telling it what to do.

This button can count!!! => 0

HTML CSS and JavaScript - How do they connect?

If a website was an orchestra, HTML and CSS would be the musicians and their instruments. JavaScript would be the conductor, guiding the different elements on a page to work together whenever they are asked to do something.

If a website was a recipe, HTML and CSS would be the ingredients and their flavours. JavaScript would be the instructions, so your recipe can be repeated over and over, and still have the same outcome.

If a website was a sports team, HTML and CSS would be the players and their different positions in the playing field. JavaScript would be the coach that will organise, strategise, and guide players through a match so they can achieve their goals.

Control flow and Loops in JavaScript

JavaScript works in a specific order and things have to be coded (written) in a way that the computer will understand and execute the lines of code the way we wanted. The code in JavaScript is run from the first line in the file to the last line. But we can control this workflow and, to change this flow, we can use conditionals and loops.

For example, we can use JavaScript to calculate the total price of a shopping cart, creating a loop that goes through every element, takes their individual prices, and sums everything.

 
        
          // Define the function
          function calculateTotalPrice(items) {
            let totalPrice = 0;
  
          // Loop through each item in the shopping cart
          for (let i = 0; i < items.length; i++) {
            // Get the price of the current item
            let itemPrice = items[i].price;
            
            // Add the price to the total
            totalPrice += itemPrice;
          }
  
            // Return the total price
            return totalPrice;
          }


          // Create an array of items in the shopping cart
          const cartItems = [
            { name: 'Shirt', price: 20 },
            { name: 'Pants', price: 30 },
            { name: 'Shoes', price: 50 }
          ];


          // Call the calculateTotalPrice function with the cart items
          const total = calculateTotalPrice(cartItems);


          // Print the total price
          console.log('Total price:', total);

         
        

Arrays and Objects in JavaScript

When it comes to structure, arrays are an ordered collection of elements that can be accessed by its numeric index. The index starts from 0 (zero) for the first element.


          const myArr = [position0, position1, position2, position3…]
        

We can access any position using the numeric index.


          myArr[0] // This will have the value 'position0' stored there.
        

Objects don’t have a specific order, but have a specific key that can be a word or a symbol.


          const person = {
            name: ‘John’,
            age: 32,
            mail: ‘john@email.com’ 
            }
        

We can access the values using the “dot” notation for objects.


          person.name // This will have “John” stored there.
        

Both Arrays and Objects can store any data type. The difference will be the way we will access the data stored, as seen above.

To iterate with Arrays, there are built-in methods like “forEach” and “map”. Objects will require additional steps like creating a “for…in” loop or “Object.keys”.

Basically, Arrays are more useful for storing and accessing ordered collections of data, while objects are best for organising and accessing data based on specific keys or properties.

Functions in JavaScript

Functions are mini, reusable pieces of a program. Having functions in your code will help it be more:

Here's an example:


          // A function to calculate the area of a rectangle
              function calculateRectangleArea(width, height) {
                return width * height;
              }

              // Call the calculateRectangleArea function with different values
              const area1 = calculateRectangleArea(4, 6);   // Returns: 24
              const area2 = calculateRectangleArea(7, 2);   // Returns: 14
              const area3 = calculateRectangleArea(10, 10); // Returns: 100

              console.log(area1); // Output: 24
              console.log(area2); // Output: 14
              console.log(area3); // Output: 100

        

Conclusions

There is a lot you can do using JavaScript, and the examples above were just the tip of the iceberg. Imagine the other things we can create and things we can manipulate using the DOM. From counting buttons to check-out shopping carts. The range of things to do is practically limitless.

This was a challenging week and having to write about it has cleared some concepts to me and I hope it helps you too. Keep on learning!