Skip to content

D010 Hello World DOM

Starting with the following HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>DOM Tasks</title>
  </head>
  <body>
    <h1 id="ov">Heading</h1>
    <button id="knap">Click me</button>
    <script src="app.js"></script>
  </body>
</html>

and the following app.js:

// a function that executes itself on load
(function(){
  // code
})();

Your task is to write code such that a click on the button changes the heading to “Hello world”.

Try:

  • Use document.getElementById to find the heading.
  • Use document.querySelector to find the button (using a CSS selector).
  • Add new functionality to the button’s onclick method: knap.onclick = function(){}; (or a lambda function).
  • Use the heading’s innerHTML property to add functionality.
Solution
(function(){
  // Find the heading using getElementById
  let heading = document.getElementById("ov");

  // Find the button using querySelector
  let button = document.querySelector("#knap");

  // Add new functionality to the button's onclick method
  button.onclick = function() {
    // Change the heading's innerHTML to "Hello world"
    heading.innerHTML = "Hello world";
  };
})();

Here is a solution based on jQuery:

$(document).ready(function () {
// Select the button and bind a click event
    $("#knap").click(function () {
// Change the heading's text to "Hello world"
        $("#ov").text("Hello world");
    });
});