const - JS | lectureDOM & Events Fundamentals

Selecting and Manipulating Elements

DOM & Events Fundamentals

Now that we understand what DOM and DOM manipulation are let's select and manipulate some more elements.

In the previous lecture, we selected the message element and it's text content by doing :

script.js
document.querySelector('.message').textContent;

Besides getting the text content of an element, we can also set the text content by doing:

script.js
document.querySelector('.message').textContent = '🎉 Correct Number!';

On saving, the text should change from 'Start guessing...' to '🎉 Correct Number!'.

That being done, let's now do the same thing for the secret number (i.e., the question mark (?)) and the score. Both of these values are stored in an element.

Back to our HTML, we can see that our secret number is a div element with a class number, and our score value is a span element with the class score. To select those two classes, we will do what we have been doing before;

script.js
document.querySelector('.number').textContent = 23;
document.querySelector('.score').textContent = 13;

Now, if you save everything, you will notice that the values have changed! Let's now do the same thing with our input value.

The input field works a bit differently in the sense that, to get its content, we don't use textContent as we've been doing, but instead, we use the value attribute .i.e.

script.js
console.log(document.querySelector('.guess').value); // Result ==> Empty result since the input field has nothing
document.querySelector('.guess').value = 23 // Setting the value of the imput field

If you now save it, you will see that the input field will be updated as if we had written it ourselves.

Now, let's say we want to log to the console any number we type into the input field whenever we click on the check button. Well, handling the click of a button is what we will learn in the next lecture.