What is DOM?
DOM stands for Document Object Model. DOM allows you to manipulate elements from the HTML file. With Javascript, you can do literally eveything on the web. DOM helps to make you HTML dynamic.
Let's say you want to create a button. With HTML alone, you wouldn't be able to do anything about it as HTML is just the structure of the web, which means, it is lifeless. SIGHS.
It is just going to be a simple button. However, if you want to add a little bit of Javascript; DOM specifically, you can add functionality to it.
Here is an example:
You may want to create a button which when you click it, a message will pop-up like "Happy Birthday!"
You can start by creating an empty element, such as < p > tag with an ID selector.
(Elements do not have to be empty all the time, this is just an example on how to manipulate things using the DOM method.)
For example:
<p id="demo"></p>
Above, you can see a < p > tag with an ID called "demo".
You then start creating a button in the HTML file with an onclick event attribute which works when someone clicks on the button. Let's say someone visited your website then they clicked the element using their mouse, the script then runs.
<button onclick="myFunction()">Click me</button>
In your Javascript file, you then use a DOM method called getElementByID(), this method returns an element with a specified value.
function myFunction() {
*// code to be executed*
}
You can see here that we created a function named “myFunction” which we took it from the HTML button. Remember, a Javascript function is defined with the function keyword (therefore, the code will not execute without it.) It is followed by a name which is the myFunction then a parentheses.
The code that is going to be executed should be placed inside curly brackets.
You can then place the DOM method inside it:
document.getElementById("demo").innerHTML = "Happy Birthday!";
We can see that the string inside the parentheses is called “demo”, which is the ID of the < p > tag in our HTML file. Which means, we are targeting that ID; we are going to manipulate it.
The innerHTML property is also part of the DOM, it allows Javascript code to manipulate contents that are being displayed.
It should look like this:
function myFunction() {
document.getElementById("demo").innerHTML = "Happy Birthday!";
}
This code basically tells us that if we click the button that we created in our html file; with the use of innerHTML, a message will pop-up as it manipulated the content of the
< p > tag; which was empty before.
Note: There are more ways to manipulate documents using the DOM method. This is just an example to show how to add elements. With the DOM, you can also create and remove elements.
Thanks for reading this blog, this is my first time so please bare with me haha. If you see any mistakes please do tell me and I will do better and correct them. Thank you! I might also cover more of this topic next time.
Have a great day! :)
-- Ash <3