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:
Your task is to write code such that a click on the button changes the heading to “Hello world”.
Try:
- Use
document.getElementByIdto find the heading. - Use
document.querySelectorto find the button (using a CSS selector). - Add new functionality to the button’s
onclickmethod:knap.onclick = function(){};(or a lambda function). - Use the heading’s
innerHTMLproperty 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: