Basic Document Object Model (DOM) Manipulation
DOM
The DOM is a standard from the W2C that breaks up a web page into a set of objects. This allows us to access each element through a bit of code!
Why do I need to know about this?
If you’ve ever thought of how you can get data from a website or how websites can change on the fly especially in response to something, that’s thanks to the DOM!
You’ll be using the DOM when working with contact forms, registration, and anything you want to dynamically change in response to the users such as the background changing after scrolling!
Accessing the DOM
Javascript can be used to access the different parts of the DOM
document.getElementById('submit') #Uses the id set in the html tag
document.getElementByClassName('submit') #Uses the class set in the html tag#Cool other syntax! Use . for class and # for IDs just like in CSS!
document.querySelector('#submit')
Remember that it’s good practice to choose one syntax to stick to and make it uniform all throughout your code.
You can then save the accessed content into a variable by adding “.value” at the end using the syntax below. This allows you to get the text content that’s in the element you navigated to.
Example:
var message = document.getElementById(‘message’).value;
You can finally store this and print this out or even send this to your backend!
Read more about it here: Access elements in the DOM
Manipulating the DOM
After being able to access the DOM, what now? Javascript can also be used to change style AND content of anything in the DOM!
Let’s say we want to hide the submit button after they click it! We would do something like this!
document.querySelector('#submit').style.display = 'none';
See how it shows the steps: style → display → value
We can also change the content of a certain tag by adding something like this:
document.getElementById(‘intro’).value = “Hello World!”;
See how it can look like here: https://dev.to/giorgosilias/manipulating-dom-in-javascript-for-beginners-4kac
Check your understanding
Try it out!
<html>
<body>
<p>Hello World!</p>
</body>
<script src="PATH TO YOUR JS FILE HERE">
</html>
Try to make “Hello World!”:
- Disappear (hint: display)
- Change Colour
- Become Bigger (hint: font size)
Conclusion
The DOM is a powerful standard that you can utilise to work with any element from a webpage. It’s an essential skill, especially when working with more complex and dynamic websites.
Next Steps
The DOM can be manipulated, but there are slightly different ways to do so. Check out frameworks next and see how they interact with the DOM such as Vue or React!
Try these exercises: https://www.w3resource.com/javascript-exercises/javascript-dom-exercises.php
Read up on it more here!