You may have heard of the DOM before, basically any pages in a browser have some objects to tell you about the state of the page, and the browser more broadly. The document object contains information about the html document/page that is currently loaded (elements, css etc), and the window object tells you more about the browser window (resolution, url etc.).
With these two objects we can make changes to the page that the user is seeing including:
- Adding, removing, and updating elements
- Sending the user to a different URL
- Change the behavior of the app based on screen size
- Make the page fullscreen
- etc.
So, let's look at some of these functionalities!
Document Object
We're going to look at the basics of just editing the HTML of an element that exists on the page. Let's take the example HTML:
<div id="result" class="result-box">
<p> There is no result </p>
</div>
Our task will be to replace the text inside the div with: "1+1 is 2". To do that we first need to find our div element. There are a few different methods for finding elements, but the one we will use this time is document.getElementById()
elem = document.getElementByID("result")
This will get an Element Object for the div element with all of its current state. We can actually see it's state by playing around with the attributes:
elem.tagName // returns "Div"
elem.className // returns result-box
elem.innerHTML // returns " There is no result
"
elem.innerText // returns "There is no result"
elem.style // returns CSSStyleDeclaration object that you can modify
So now that we can get the attributes all we have to do to modify the page is change the values. In our case we can just change the innerHTML to match the output we want:
elem.innerHTML = "1+1 is 2
"
Window Object
This object has a ton of information about the browser, for today we're just going to look at using it to redirect people to a different URL. To do this we need to access an attribute that is its own object called Location.
window.location // Location Object
The Location object then has an attribute called href that is our URL
window.location.href // A string representing the URL
Then just like with the document object, changing this attribute will update the page, so we can send people to https://schulichignite.com/ using
window.location.href = "https://schulichignite.com/"