Skip to content

Browser APIs

The browser allows us to use JavaScript in order to interact with the DOM we discussed on day 1. Let's see how we can do some simple operations with it!

Manipulating the DOM

We can manipulate the DOM by using functions available in the document global object:

1
2
3
4
5
6
const body = document.querySelector('body') // Get the page body, or any other HTML element
let testDiv = document.createElement('div') // Creates a div element

testDiv.textContent = 'I am a new div!' // Set the inner content of a div

body.appendChild(testDiv) // Adds the div as a child to the page

Try running the code above on a blank page and see what happens!

Event listeners

Apart from adding elements to the DOM, we can also listen to certain events. For example, assuming we have this HTML:

1
2
3
4
5
<body>
  <div class='clickme'>
    Click me!
  </div>
</body>

We can use the following JavaScript code to trigger a message to the user when the div is clicked:

1
2
let div = document.querySelector('.clickme') // Get the Div
div.addEventListener('click', () => alert('Hello!))