JavaScript – What is the DOM & DOM Manipulation? [2023]

The Document Object Model – is a structured representation of an HTML document.

You can use the DOM to “connect” HTML to CSS and JS.

The DOM is often said to have a tree structure or a hierarchy like a family with children and parents

Image source

Selecting & Manipulating Elements with JavaScript

You can use “document” to ‘enter’ the document – as in the top level of the HTML document as shown in the tree diagram above.

  • use “querySelector” to select a specific element in the DOM.

For example document.querySelector(‘.message’).textContent

Will select the text content of the element with the class of “message”

Once you have selected the content, use the equals sign = to update it.

document.querySelector(‘.message’).textContent = ‘Correct Number!’

The ‘code’ on the line above, will change the text-content found in the element .message to “Correct Number!”

“textContent” will only work if the element is something like a paragraph, that holds content.

If you have a value input field, like on a form or something similar, you may have to use .value instead of .textContent

document.querySelector(‘.guess’).value = 23;

The code on the left, adds “23” as the input value to the form/input field on the right^

Screenshot from The Complete JavaScript Course

Handling Click Events

In this example, the button has a class of “check”

document.querySelector(‘.check’) – will select the button with the class of “check”

Then we need to use the addEventListener() method. The addEventListener method, basically looks out for events such as button clicks.

Image Source

Event Listener ^looks out for events such as button clicks.

We can add the event we want to look out for, in this example a click:

addEventListener(‘click’)

  • Now we need to tell the event listener what to do what it observers a click

addEventListener(‘click’ function () {
console.log(document.querySelector(‘.guess’).value);});

The code in bold, will take the value from the element called “guess” and print it to the “console.log”.

Screenshot from The Complete JavaScript Course

The code above prints 9 to the console.log

the element with the class of “guess” is the form input field containing the number 9:

Adding “Game Logic”

The aim of game in the screenshot above – guess the secret number

We need to randomly create a number and then tell the user when the number they guess is too high, too low or correct.

  • Producing the secret number

const number = (Math.truncMath.random()*20)

Math.random gives a number between 0 and 1

Match.trunc rounds up or down the number to the nearest whole number.

Multiplting the random number by 20 makes the number, well, larger

  • Checking the User Input Vs the Secret Number

if (!guess) {

document.querySelector(‘.message’).textContent = ‘No Number’;}

else if (guess === secretNumber) {

document.querySelector(‘.message‘).textContent = ‘Correct Number!’;

}

The code above will print “No number” if a number isn’t entered into the relevant form field.

if the number entered (the guess), is equal to the secretNumber – then the code will print “Correct Number!” – to the element with the class of “message“.

What if the guess is greater than the Secret Number?

else if (guess > secretNumber) {

document.querSelector(‘.message’).textContent=’Too high!’

and if it’s too low:

else if (guess < secretNumber) {

document.querSelector(‘.message’).textContent=’Too low!’

So all the code together will look like:

Adding a Score to The Game

The score will start at 20 and decrease for every wrong guess.

So, if the user guesses too low, reduce the score by 1

We also need to add a variable for the original/starting score, after the secretNumber is declared (or the code to create the secretNumber anyway)

Declare the score with:

let score = 20;

The score is part of the “application state”. The score is available in the code and not just in the DOM

Game Over

To tell the player when they’ve lost the game, we need to add a condition related to the score variable:

if (score > 1) {

https://www.udemy.com/course/the-complete-javascript-course/learn/lecture/22648419#learning-tools

Manipulating CSS When Player Wins- Change Background Colour

First select the whole <body> element

document.querySelector(‘body’).style.backgroundColor = ‘#60347’;

Implementing a High Score ‘Box’

Just like the regular, current score, we need to store the high-score in a variable.

use the code

let highscore = 0;

We need to check if the current score is greater than the existing game’s score

if (score > highscore) {

highscore = score;

}

Assuming the “HighScore” Box has already been made – we need to check what the class is.

In the this case, the class = “highscore”

Now we need a way to update the highscore, when the current score is greater.

document.querySelector(‘.highscore’).

textContent = highscore;

https://www.udemy.com/course/the-complete-javascript-course/learn/lecture/22648427#learning-tools

Getting Rid of Duplicate Code (DRY Principle)

The code if the guess is too high, or if the guess is too low code is pretty much duplicate code

Remember

Dont Repeat Yourself DRY

There’s no problem starting out with repeated code, and then refactor the code once it’s all working

  • ID duplicate or close-duplicate code
  • Refactor the facker

Change the code above, to a “when guess is wrong” code block.

Use a ternary operator

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s