Javascript Flashcards
Method for finding elements without using getElementById
document.querySelector(“#id”);
Property that represents the HTML text between an elements opening / closing tag
element.innerHTML = “text”;
What version of querySelector finds all of the elements with a given tag?
document.querySelectorAll(“.class”);
What is the traditional way of getting an element via ID?
document.getElementById(“myid”);
NOTE no # for the id
How do you change the CSS style of an element?
element.style.color = “red”;
Write code to create a P element and append it to the end of the body element.
var p = document.createElement(“p”);
document. body.appendChild(p);
p. innerHTML = “Hello World!”;
How would you set an attribute on an element that you have created through code?
p.setAttribute(“id”, “example”);
How do you remove an element from a page?
p.parentNode.removeChild(p);
This will effectively remove itself (but note that it has to go through the convoluted path of getting it’s parent then having parent delete the node)
Write code to set a “click” handler on a button element?
var but = document.querySelector("button"); but.addEventListener("click", clickHandler, false);
How do you remove an event listener?
but.removeEventListener(“click”, clickHandler, false);
How do you produce a random number between 1 and 10?
var num = Math.floor((Math.random()*10) + 1); or var num = Math.ceil(Math.random() * 10);
Convert a string into an int.
var num = parseInt(input.value);
How do you determine if a value is a string?
if (isNaN(variable)) { // Do something appropriate }
How do you disable a button in code?
var button = document.querySelector("button"); button.disabled = true;
How could you use Math.random() to give a random true / false result?
if (Math.round(Math.random() === 1) { // True } else { // False }
How would you create a random number between 10 and 25?
Math.floor(Math.random() * 16) + 10;
What is some limitations of an object literal?
It is a singleton and also cannot implement the concepts of encapsulation, and inheritance. It also doesn’t require the use of new to create it.