In this episode, we will be getting to the grips with some of the very basics. The only assumption we will make about your current knowledge is that you know at least some basic HTML/CSS. If you don’t then please take a look at my HTML/CSS Noob to Pro tutorials.
So for those of you who don’t know already if you press F12 (or right click on a page then go to inspect) then you will be presented with some developer functionality built into your browser. At the moment we are interested in the console.
The console is typically used for debugging. It allows you to print out arrays behind the scenes without any HTML getting in the way.
So first off let’s see if we can print out “Hello World!” into the console.
Inside our script tags, we will add “console.log(‘Hello World!’);” like so
Now if you open your console and refresh the page you should see “Hello World!”.
Now it would be pretty boring if we ended things here so let’s look at printing this out to the DOM.
The DOM, aka “Document Object Model” is essentially just what you see in your browser.
So let’s create a div with the id of “change-me” and in our JS we can run “document.getElementByID(‘change-me’);” to select this element.
By itself, that won’t do anything, but say we want to console log what is inside the chosen element. We can do that by appending “.innerHTML” and sticking the whole thing inside our “console.log” like so.
Now you should see “I am a DOM element in your console”.
Now if we want to change text we just have to assign it to a new value.
So let’s remove the “console.log” for now and after the “innerHTML” we can add ” = ‘Hello World!’;”.
If you refresh your page now then you should see the words change instantly from “I am a DOM element” to “Hello World!”;
But usually, you would want to do something like this on something else being actioned on the page rather than on the screen loading. So let’s add a button and see if we can change the words once the button is clicked.
So now if you load the page you should be greeted with “I am a DOM element”, then once you click the button it should change to “Hello World!”.
Then we added all this to happen on an on click action by using the HTML attribute “onclick”.
In the next episode, we will take a look at adding variables and functions to our script.