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
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.
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: