Group Chat Week 4 Solutions
Well done if you got these right!
-
What do all of the variables contain in this code?
- An object representing the
h1
title node in the DOM. - null - the CSS selector of “text” will look for the TAG with the name “text”. If we wanted the
<p>
tag, we should have useddocument.querySelector("p")
ordocument.querySelector("#text")
- An HTML collection of all images on the screen. This is sort of like an array, and should contain just one item (an object representing the image in the DOM).
- An object representing the
-
Why doesn’t this code change the h1 tag to red?
- We’re setting an attribute of color here, not a style!
- To set a style, we need to use
title.style.color = "red"
-
Why doesn’t this code (different) change the h1 tag to red?
document.querySelectorAll
returns a node list (an array of nodes), not a single node. We can only reassign properties like this of an object, not an array of objects.- The first line needs to look like:
const title = document.querySelectorAll("#title")[0]
-
What is this code trying to do, and why isn’t it working?
- The code is trying to add a new
<p>
tag to the screen saying “WOOF! X clicks!” every time the image of the dog is clicked. - It isn’t working, because we forgot to actually attach the newly created element to the screen! To do this, we’ll need to grab hold of the body node, and then use the
element.appendChild()
method to add ournewParagraph
onto it.
- The code is trying to add a new
-
Why does the output break when we press the submit button in this code?
- With forms, since we’re using a button with a type of “submit”, the default behaviour is that the page will try to submit the form to the address on the server corresponding to the “action” attribute. In this case, we didn’t give anything, so the page will just reload at the same address (causing an editor within an editor).
- We need to call the
event.preventDefault()
method as soon as the event handler function starts to stop this default behaviour.