Blog

DOM Objects in JavaScript

Lectori salutem.


There were several concepts we learned about regarding how to use JavaScript, with DOM objects arguably being one of the most important. This is how they work.


DOM objects are the link between using HTML and using JavaScript. The whole point of using JavaScript is to make your webpage capable of doing actions, and DOM objects allows JavaScript to interact with elements from the HTML portion itself, which is what the user sees. Arguably, the most important part of the JavaScript code here is the "getElementById(id)", which makes a JavaScript object based off of an HTML element. Take this example from my own practice work.

const h1 = document.getElementById("main-heading");

What this does is that it makes a variable in JavaScript called "h1"(often used for headers in HTML) and it looks for any HTML element that has the ID attribute of "main-heading". There are other ways of doing this, as there are other "getElementBy..." functions, including ones which allow you to get a handle of several at once.

This in turn allows you as the programmer to interact with the HTML page using the JavaScript coding. For a simple example, see this:

h1.style.color = "red"

What this essentially does is that it changes the color of the header's text by using JavaScript to change its value. Now, this is a very simple example of something you can do with this, but there is lots which can be added on to this. You can make it so it turns red because it reacts to the user clicking or hovering on it, or it could do so in response to another element being interacted with. Truly, this is only limited by what you know as the programmer.