Five things can happen when a person gets hold of a calculator. They can hit:
a number key (0–9)
an operator key (+, -, ×, ÷)
the decimal key
the equals key
the clear key
The first steps to building this calculator are to be able to (1) listen for all keypresses and (2) determine the type of key that is pressed. In this case, we can use an event delegation pattern to listen, since keys are all children of .calculator__keys.
Add this calculator.js file
const calculator = document.querySelector(‘.calculator’) const keys = calculator.querySelector(‘.calculator__keys’)
The above code contain querySelector.For you to understand what that is let us talk about DOM
Introductin to DOM¶
The Document Object Model, or DOM for short, is a platform and language independent model to represent the HTML or XML documents. It defines the logical structure of the documents and the way in which they can be accessed and manipulated by an application program.
You can select:
the top most elements that is the html, body, head
Element by id
Element by class name
Element by tag name
Elemnet by css selector
Selecting element top most element¶
The topmost elements in an HTML document are available directly as document properties. For example, the element can be accessed with
document.documentElement property, whereas the
document.headproperty, and the element can be accessed with
Open the Devtool on your and try out the following.To open the devtool If you are using chrome and you are on linux or window
Ctrl + Shift + C and if you are using firefox
Ctrl + Shift + I or
You should see output like this
Get the body content by typing
document.body under the console option.
Try changing the background color of the body to your favorite color mine is black so I will change like so
document.body.style.background = "black"
Notice the color change.
Selecting element by class name¶
You can use the
getElementsByClassName() method to select all the elements having specific class names. This method returns an array-like object of all child elements which have all of the given class names.
class = document.getElementsByClassName("md-footer-social")
You can assign the result of the above to a variable and try to get is length
Selecting Elements by Tag Name¶
You can also select HTML elements by tag name using the getElementsByTagName() method.
1 2 3 4 5 6 7 8 9 10 11
<html> <body> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "Hello World!"; </script> </body> </html>