JavaScript

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

1, 3

"captain" has been assigned to someWord. You want to slice "ap" out of it. Fill in the blank. var segment = someWord.slice(___);

default : bar = 2;

Code 2 lines of a switch statement that specify that a variable (already declared) is assigned a number if no specific cases are true.

<input type="button" value="Say hi" onClick="alert('Hi');">

Code a button that says "Say hi" along with a alert when clicked saying "Hi"

comparison

===, !==, >, and <= are ________ operators.

window.open();

A full-size blank window will open. Complete the code. var greatBigWindow = ____________

constructor

A function that creates objects and their properties is known as a _______ function.

method

A function that's attached to an object is known as a _______.

newLink.setAttribute("href", "http://www.wikipedia.org");

A new <a> node has been created and assigned to the variable newLink. Add an attribute to it that takes the user to wikipedia.org when clicked.

switch

A switch statement begins with the keyword _________.

local

A variable declared in a function is a ________ variable.

global

A variable declared in the main code is a ______ variable.

txt.appendChild("moreTxt");

Add a text node represented by a variable of your choosing to a parent represented by another variable of your choosing.

"zbc abc"

After these two statements execute, what is the value of x? Include quotation marks. var x = "abc abc"; x = x.replace("a", "z");

"zbc"

After these two statements execute, what is the value of x? Include quotation marks. var x = "abc"; x = x.replace("a", "z");

info.document.write(content);

An HTML string has been assigned to the variable content. Load the string into a window whose handle is info.

var links = keyParagraph.getElementsByTagName("a");

Assign a list of links in the paragraph represented by the variable keyParagraph to the variable links, which hasn't been declared beforehand.

var el = document.getElementById("p1"); el.onmouseover = doIt;

Assign an element with an id of your choice to a variable of your choice. When the user mouses over the element, run a function with a name of your choice.

document.getElementById("p60").className += " special";

Assign the class "special" to the paragraph with the id "p60"

var txt = document.getElementById("div1").innerHTML;

Assign the contents of the div with the id "div1" to the variable txt, which hasn't been declared beforehand.

var p = document.getElementById("slide0"); p.src = "cat.jpg";

Assign the element with an id of "slide0" to the variable p, which hasn't been declared beforehand. Assign "cat.jpg" to the element as its source.

var c1 = d.childNodes[0]; var t = c1.nodeType;

Assign the first child of the div represented by d to the variable c1. Assign the node type of the child to the variable t. Neither c1 nor t has been declared beforehand.

classPic.src = "pic2.gif";

Assign the source "pic2.gif" to the element represented by the variable classPic.

var foo = document.getElementById("myField").value;

Assign the value in a field with an id of your choice to a variable, which hasn't been declared beforehand.

if (nodeToCheck.nodeName === "#text") { var content = nodeToCheck.nodeValue; }

Check the name of the variable nodeToCheck to see if it's a text node. If so, get its text content (value) and assign it to the variable content, which hasn't been declared beforehand.

document.getElementById("age").value = "";

Clear a field with an id of "age"

document.getElementById("foo").innerHTML = "";

Clear a paragraph. Make up the id.

faq.close();

Close a window whose handle is faq

<input type="text" onFocus="colorField();" onBlur="uncolorField();">

Code a text field. When the user clicks in it, a function executes. When the field loses focus, a different function executes.

<input type="text" onFocus="myFunc();">

Code a text field. When the user clicks in it, call a function.

myMethod: function(parm1, parm2) {

Code the first line of a method with 2 parameters.

switch (city) { case "Akron" :

Code the first two lines of a switch statement that tests the variable city. The first case tested is "Akron"

switch(country) { case "Spain" :

Code the first two lines of a switch statement that tests whether a particular string of your choice has been assigned to a particular variable of your choice.

case true :

Code the second line of a switch statement that tests for a boolean

<img src="foo.gif" id="bar" onClick="foobarred();">

Code the tag for an image that, when clicked on, executes a function. Code in this order: image source, id, event handler.

What is the window.location object?

The location object contains information about the current URL, and is part of the window object and is accessed through the window.location property.

var foo = contentDiv.getElementsByTagName("img");

The statement makes a collection of all the images in the div represented by the variable contentDiv and assigns the collection to pics. Fill in the blank.

product332.caseQty = 6;

There is a prototype property, caseQty, for the constructor Product. Its value is 12. Make an exception for product332. Its caseQty is 6.

prototype

This is the first line of a prototype statement that creates a prototype method for the constructor MakeObj. Fill in the blank. MakeObj.________.calcTax = function(price) {

pets.splice(1, 2, "bird", "bear");

This statement created the array: var pets = ["dog", "cat", "ox", "duck", "frog"]; Add 2 elements after "dog" and remove "cat", "ox", and "duck".

e.className += " special"; //note the space

To any classes that are already assigned to the element represented by the variable e, add the class "special".

equal sign. item on left is attribute name, on right is value <input type="text" <div id="d1"

To find DOM attributes, what do we look for in the markup?

LC

Two characters in this code are incorrect. Type the two correct characters. var allLower = userInput.tolowercase();

[]

Type the characters that are incorrect. var cha = sentence.charAt[10];

()

Type the characters that are missing from this code. var allLower = userInput.toLowerCase;

}

Type the last line of a switch statement.

<body>

Type the opening tag for the last required element node.

getTime You start with milliseconds, then convert it to days, hours, or whatever you need.

What is the keyword for extracting the basic time unit you need for figuring intervals?

getDate

What is the keyword for extracting the day of the month?

getMilliseconds

What is the keyword for extracting the smallest unit of time that JavaScript recognizes?

getFullYear

What is the keyword for extracting the year?

charAt

What is the keyword for finding a character at a particular location in a string?

lastIndexOf

What is the keyword for finding the index of the first character of the last instance of a segment?

replace

What is the keyword for removing one set of characters and inserting another set in its place?

prototype

What is the keyword that allows all objects created by a particular constructor to share the same property or function?

break

What is the keyword that stops a loop from continuing to loop?

onClick

What is the keyword that tells the browser to watch for a click on a link?

there are 2 options: 1) put inside script tags like so: <script> Var add = function(x,y) { Var z = x+y; Return z } Var sum = add(2,3); Alert (sum); </script> 2) add a reference to a .js file like so <script type="text/javascript" src="Scripts/tests.js" async></script>

Whats the syntax for adding javascript to your html page?

<form id="frm1" onSubmit="return val();">

Write the opening tag for a form whose id is "frm1" that executes a validation function, val, when the form is submitted.

<button onclick="myFunction()">Click me</button>

code a button named "Click me" that calls myFunc function on click

<form> <input type="text" value="email"> <input type="submit" value="submit"> </form>

code a simple form with no event that collects an email address (no validation) and has a submit button

var style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = '.cssClass { color: #F00; }'; document.getElementsByTagName('head')[0].appendChild(style); document.getElementById('someElementId').className = 'cssClass';

create a css class using javascript named 's' apply that style to all list items on a page

var dog = { name: "boone", breed: "hound" };

create a dog object with name and breed properties

function myFunction() { var x = document.createElement("STYLE"); var t = document.createTextNode("body {font: 20px verdana;}"); x.appendChild(t); document.head.appendChild(x); }

create a function that places a style element in the head and makes all text in the body 20px verdana

var sum = Number(num1) + Number(num2);

num1 is "1", num2 is "3". Rewrite this statement so sum is assigned 4. var sum = num1 + num2;

var userCity = document.getElementById("city").value;

Assign the value in the field with an id of "city" to the variable userCity, which hasn't been declared beforehand.

<p>

Assuming that junk artifacts have been cleaned from the DOM, what is the second child of the first element node? <div> <h3>Age-old problem</h3> <p> So many nodes, so little time. </p> </div>

5 div, h3, heading text, p, paragraph text

Assuming the DOM has been cleaned of junk artifacts, how many nodes are in this markup? (Answer with a numeral.) <div> <h3>Age-old problem</h3> <p> So many nodes, so little time. </p> </div>

Bar.prototype.method = function(e) { this.alert(e); }

Bar.prototype.method = function(e) { this.alert(e); }

function MakeObj(color) { this.color = color; } var thing = new MakeObj("blue"); MakeObj.prototype.displayColor = function() { alert(this.color); }; thing.displayColor();

Code a constructor function that creates an object with one property. Call the function to create an object, passing a value for the property. Code a prototype method that displays the object's property. Call the method

for (var i = 0; i < oList.length; i++) oList[i].className = " myStyle"; }

Code a for loop that cycles through the first 3 elements of a list, which has been assigned to a variable, and assign a class to each of them. Use the most common loop specifications.

for (var i = 0; i <= 2; i++) { contents[i] = paragraphList[i].innerHTML; }

Code a for loop that cycles through the first 3 paragraphs of a list, which has been assigned to an array of your choosing, and assign the text contents of each paragraph to an array item. Use the common loop specifications. This statement creates the array that collects the text contents: var contents = [];

var est = doSomething(foo, barred(10));

Code a function call - doSomething - that has two arguments. The first argument is a variable. The second argument is another function call - doThis. The second function call takes the argument 10. The value returned by the first function is assigned to est, which hasn't been declared beforehand

foo(barr, "a string", 34);

Code a function call that takes a variable, a string, and a number as arguments.

function imgSwapper(id, img) { var myImg = document.getElementById(id); myImg.src = img; }

Code a function that assigns a new image source to an image element. The ID of the image element is the first parameter. The path to the image source is the second parameter. First assign the image element to a variable that hasn't been declared beforehand. Then assign the new image path to that variable.

MakeObj.prototype.dispMess = function() { alert(this.message); };

Code a method prototype that displays a message. The message text is passed to the method by the constructor, not the statement that calls the method.

MakeObj.prototype.dispMess = function(message) { alert(this.message); };

Code a method prototype that displays a message. The message text is passed to the method by the constructor, not the statement that calls the method.

MakeObj.prototype.dispMess = function(message) { alert(message); };

Code a method prototype that displays a message. The message text is passed to the method by the statement that calls the method, not by the constructor.

Part.prototype.brand = "Acme";

Code a prototype property called brand for a constructor called Part. Its value is "Acme"

alert(new Date("January 1, 1980").getTime());

Code a single statement that displays in an alert the milliseconds that elapsed between the reference date and the beginning of 1980.

var foo = getTime() / (1000 * 60 * 60);

Code a statement that converts the milliseconds represented by ticks to hours and assigns the result to a variable that hasn't been declared beforehand.

var secsSince = d.getTime() / 1000;

Code a statement that determines the seconds since midnight, Jan. 1, 1970 and assigns it to a variable that hasn't been declared beforehand. Use any variable you like to represent the Date object. Note that I'm asking for seconds. Don't round it.

window.location.replace("http://www.foo.com");

Code a statement that directs the browser to a new URL (make up the name) and excludes the current page from the browser history.

window.location.reload(false); the word false is not mandatory... its the default if no parameter given.

Code a statement that explicitly, using a Boolean, tells JavaScript to refresh the current page from the cache if the page is cached.

var x = d.getDay();

Code a statement that extracts whether it's Monday, Tuesday, etc. (as a number) from the Date object represented by d and assigns it to x, which hasn't been declared beforehand.

return someVarDeclaredInFunction

Code a statement that passes the value of a variable declared in the function to a global variable that was declared in the calling statement that resides in the main code.

foo = foo.toFixed();

Code a statement that rounds a number represented by a variable to no places, converts it to a string, and assigns it to the same variable.

var dec3 = n.toFixed(3);

Code a statement that rounds a number represented by n to 3 places, converts it to a string, and assigns it to dec3, which hasn't been declared beforehand.

var intgr = n.toFixed();

Code a statement that rounds a number represented by n to no places, converts it to a string, and assigns it to intgr, which hasn't been declared beforehand.

var c = "b" in a;

Code a statement that tests whether the object a has a property b, and assign the result to the variable c, which hasn't been declared beforehand.

<input type="text" onBlur="this.style.backgroundColor = 'white';">

Code a text field. When it loses the focus, the field turns white.

<input type="text" onFocus="this.style.backgroundColor = 'yellow';">

Code a text field. When the user clicks in it, the field turns yellow.

function MakeDog() { } MakeDog.prototype.doNothing = function() { };

Code an empty constructor function. Then give it a prototype method that has no parameters and does nothing.

var greeting = { sayHi: function() { alert("Hello world!"); } };

Code an object that has a single method that displays an alert with a text message.

var nonentity = { doNothing: function() { } };

Code an object that has a single method that doesn't do anything.

var foo = { myNum: 2, myMethod: function() { return this.myNum * 10; } };

Code an object that has one property, a number, and one method. The method multiplies the property by 10 and sends the result back to the calling code. Don't refer to the object by name in the method.

window.location.assign("http://www.whee.com"); ...or... window.location.replace("http://www.whee.com");

Code either of the alternatives taught in this module that you can use instead of... window.location.href = "http://www.whee.com";

default :

Code the catch-all clause that specifies what happens if none of the above cases is true.

switch(foo) { case 1 : bar = true; break;

Code the first 4 lines of a switch statement that tests to see if a variable is assigned one number or another. If the first test passes, a variable (already declared) is assigned a Boolean value.

for (var j = 0; j < 100; j++) {

Code the first line of a for loop with a counter name that's not i. Code the usual starting value and usual increment. Run it 100 times using < to specify how many loops.

for (var i = 0; i > -3; i--) {

Code the first line of a for loop with the usual counter and the usual starting value. Run it 3 times using > to specify how many loops. Decrement it with each iteration.

for (var i = 0; i < 4; i++) {

Code the first line of a for loop with the usual counter name, usual starting value, and usual increment. Run it 4 times using < to specify how many loops

if ("prop" in obj) {

Code the first line of an if statement that checks to see if an object has a particular property.

if (document.getElementById("myField").value === "some text") {

Code the first line of an if statement that tests for a text value of your choice in a field.

if (targetNode.nodeValue === null) {

Code the first line of an if statement that tests if the value of the node assigned to the variable targetNode is null.

if (indexNum !=== -1) {

Code the first line of an if statement that tests whether a segment with an index represented by indexNum exists in a string.

if (document.getElementById("p3").childNodes[0]) {

Code the first line of an if statement that tests whether an element with the id "p3" has any child nodes by testing whether it has a first child node.

if (d.getHours() < 12) {

Code the first line of an if statement that tests whether it's before noon. Use d to represent the Date object - which has already been created.

if (d.getMinutes() === 0 && d.getSeconds() === 0) {

Code the first line of an if statement that tests whether the clock is at an hour on the dot. Check minutes and then seconds. Ignore milliseconds. Use any variable you like to represent the Date object.

if (document.getElementById("field1").value.length === 0) {

Code the first line of an if statement that tests whether the field with an ID of field1 is empty.

if (obj.hasOwnProperty("color") {

Code the first line of an if statement that tests whether the property "color" was explicitly assigned to an object as opposed to inherited.

if (plan2.hasOwnProperty("color")) {

Code the first line of an if statement that tests whether the property "color" was explicitly assigned to an object as opposed to inherited.

if (document.getElementById("e1").attributes[1]. nodeName !== "class") {

Code the first line of an if statement that tests whether the second attribute of an element with the id "e1" is not class.

if (addr.indexOf(".") < addr.length - 2) {

Code the first line of an if statement that tests whether there are at least 2 characters after the dot in a string represented by a variable. Use the length of the variable to measure. Dont use regular expressions.

if (val.indexOf(".") - val.indexOf("@") < 2) {

Code the first line of an if statement that tests whether there is not at least one character separating the "@" and the dot in the string represented by a variable.

var newStr = str.replace(/1/g, "one");

In a string represented by str replace all instances of "1" with "one" and assign the revised string to newStr, which hasn't been declared beforehand.

var newStr = str.replace("1", "one");

In a string represented by str replace the first instance of "1" with "one" and assign the revised string to newStr, which hasn't been declared beforehand.

toFixed()

The keyword that rounds a number to a specified number of decimal places and converts it to a string is _____.

return

The keyword that sends data back to the calling code is ______.

str.length - 1

The last character of the string is assigned to the variable. Fill in the blank, using the string length to specify the index. var lastChar = str.charAt(________);

str.length -1

The last character of the string is assigned to the variable. Fill in the blank, using the string length to specify the index. var lastChar = str.charAt(________);

Hello nodeValue

We want the value of the first child of the p element <p>Hello<strong>world</strong></p> what is that value and what keyword would get it?

inline script

What 2 words would describe the coding method used below <a href = "#" onClick = "alert("hello"); var foo = 3;">Click Me</a>

form

What HTML tag encloses onSubmit? Don't include the brackets in your answer.

else if

What are the keywords that test for a condition when all tests above it have failed?

1 Fetch the HTML page (e.g. index.html) 2 Begin parsing the HTML 3 The parser encounters a <script> tag referencing an external script file. 4 The browser requests the script file. Meanwhile, the parser blocks and stops parsing the other HTML on your page. 5 After some time the script is downloaded and subsequently executed. 6 The parser continues parsing the rest of the HTML document.

What are the steps a browser takes to load a script that is not async

Array of childNodes

What data type does this return - assuming n is a node in the DOM? var foo = n.childNodes;

property

What do you call a value that is attached to an object? (one word)

a 16 digit decimal between 0 and 1, but not including 1

What gets assigned to var randomNumber = Math.random();

slice

What is a method for extracting a segment from a string?

Variables can be used before they are declared x=3 console.log(x); //logs 3 var x; //declares x initialization however doesn't get hoisted. The code below yields undefined for y. <!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var x = 5; // Initialize x var y; // Declare y elem = document.getElementById("demo"); // Find an element elem.innerHTML = x + " " + y; // Display x and y y = 7; // Assign 7 to y </script> </body> </html>

What is hoisting in javascript?

getTime();

What is the code for extracting the milliseconds since midnight, Jan. 1, 1970?

className

What is the html element property that can be used to modify the appearance of the html element?

setAttribute("class", "pretty");

What is the keyword for adding class = "pretty" to an image tag? You want to eliminate all other classes in the class collection.

appendChild

What is the keyword for adding text content to a paragraph?

toString

What is the keyword for converting a number to a string?

Number

What is the keyword for converting an integer string or floating-point number string, to its equivalent number?

createElement("div");

What is the keyword for creating a new div?

onBlur

What is the keyword for detecting that a field no longer has the focus?

onFocus

What is the keyword for detecting that the user has clicked in a field?

onSubmit

What is the keyword for detecting that the user has submitted a form?

indexOf

What is the keyword for finding the index of the first character of a segment?

100

What is the minimum number of pixels in the width and height parameters? Answer with a numeral.

#text

What is the node name of the first child of the element? <p>Hello world!</p>

1

What is the result (in the console) of this statement? console.log(parseInt("1.6"));

<html>

What is the second level of the DOM? (lowercase)

name

What is the second parameter of the window.open method? Answer with one word.

/* commented code here more commented code */

What is the syntax for commenting in bulk?

document.createElement("STYLE");

What is the syntax for creating a css style element in javascript?

DOM

What is the three-character designation for the organization chart of a web page?

string

What is the type of foo below: var foo = num.toFixed();

no!

What is the value of lowerVersion? Include the quotation marks in your answer. var lowerVersion = "NO!".toLowerCase();

1

What is the value of roundedNum? var roundedNum = Math.floor(1.9);

backspace

What keypress has the same effect as history.back()? Answer with lower-case characters.

push ex: dogs.push("Clancy", "Hoover");

What keyword adds one or more elements to the end of an array?

slice

What keyword copies elements from an array to another array?

splice

What keyword inserts new elements anywhere in an array and/or removes elements from an array?

shift unshift

What keyword removes the first element of an array what keyword adds to the first element of an array

pop ex: dogs.pop();

What keyword removes the last element from an array?

else

What keyword specifies an action when all tests above have failed?

document

What node in the DOM has no parent?

src

What property of an image element do you change if you want to swap the image with another

element

What type of node do you see first here? <div> <h3>Age-old problem</h3> <p> So many nodes, so little time. </p> </div>

text

What type of node has no children?

text

What type of node is the fifth one you see here? <div> <h3>Age-old problem</h3> <p> So many nodes, so little time. </p> </div>

true window.location.reload(true);

What word forces the browser to reload the page from the server?

history

What word is used in all statements that move the browser backward and forward?

%

Whats the character for modulus (remainder of dividing 2 numbers)

variable

When a function sends data back to the calling code, the calling code needs something to catch it. That something is usually a ________.

<img src="click.png"

When the image click.png is clicked, an alert displays saying, "You clicked the pic" Fill in the blank. ________________ onClick="alert('You clicked the pic');">

2

When the statement finishes executing, what is the value of performers? var group = "duo"; switch(group) { case "solo" : performers = 1; case "duo" : performers = 2; case "trio" : performers = 3; }

onBlur="gone();">

When the text field loses the focus, the function gone executes. Fill in the blank. <input type="text" ___________________________

myImg.onmouseout = foo;

When the user moves the mouse off an image represented by a variable of your choice, a function with a name of your choice executes.

value

When validating text boxes in fields that must be filled out, what property of the text box element do we typically check? One word.

constructor

When you see this line of code, you know it's part of a _______ function. this.doSomething = function() {

Anywhere as long as the asynch or defer keyword is in the markup. This tells the browser to not wait until the js has loaded before rendering the page. In old days - would put it after </body> - if the code was embedded. http://stackoverflow.com/questions/436411/where-is-the-best-place-to-put-script-tags-in-html-markup

Where should the script tags go in an html document?

increases speed and reduces size of objects since there is no redundant code

Why have method or property Prototypes

"/en-us/windows/gaming"

https://www.microsoft.com/en-us/windows/gaming Look at the URL shown above and tell me the value of currentPage. It's a string, so enclose it in quotes. var currentPage = window.location.pathname;

d1.insertBefore(p1, d1.firstChild);

i want to insert a new paragraph into a div that already has 5 paragraphs. I want the new paragraph inserted between the 2nd and 3rd paragraph. What is the syntax used to do this? div is represented by d1 new paragraph represented by p1

don't use += when assigning a className to the element, instead use =

if you want to remove all other className assignments to an element in favor of a new className called "foo"

calcObvious: function () {

in an object without prototypes, Code the first line of a method, calcObvious.

document

in the DOM, What type of node contains all other nodes?

.src = "after.png";

The existing image is replaced by "after.png". Fill in the blank. document.getElementById("pic1")________________

document.getElementById(picId).src = "nextPic"; //remember not to quote the elementId since its passed in.

The first line of the function is... function swap(picId, nextPic) { The function substitutes the image represented by nextPic for the original image that has an id represented by picId. Code the line that makes the swap. Include the indent.

function calc(a, b) {

The function call is: calc("Funds received", 500000); Code the first line of the function.

createTextNode

What is the keyword for creating a string that will be the child of a paragraph?

attribute

In the markup below src="http://www.wikipedia.org" is an _______ of the element img. <img src="http://www.wikipedia.org">

null Unlike a text node, the node value of an element is always null.

In the markup below, what is the node value of the element? <img src = "http://www.wikipedia.org">

null unlike a text node the nodeValue of an element is always null.

In the markup below, what is the node value of the element? <img src = "http://www.wikipedia.org">

selectedValue

In the markup for a selection box, the ID is assigned to...

head and body

Name the levels under the html level of the DOM. (lowercase)

var numStr = num.toString();

Convert the number represented by num to a string and assign the string to numStr, which hasn't been declared beforehand.

var foo = new Date("January 1, 2016");

Create a Date object for the first day of 2016

var earlyTime = new Date("January 1, 1901 00:00:01");

Create a Date object for the first second of the first day of the first month of 1901 and assign it to a variable that hasn't been declared beforehand.

var foo = document.createElement("div");

Create a div and assign it to a variable of your choosing, which hasn't been declared beforehand.

function changeClass() { var biguns = document.getElementsByTagName("h1"); for (var i = 0; i < biguns.length; i++) { biguns[i].className += "myStyle"; } }

Create a function called changeClass that will change the CSS class of all h1 elements

var foo = new Date(); //console.log(foo.getHours()); foo.setHours(6); console.log(foo.getHours());

Create a new date object, then set the hours to 6, then log the modified hours out to the console.

var newP = document.createElement("p"); var newT = document.createTextNode("Hello world"); newP.appendChild(newT); parentElement.insertBefore(newP, existingE);

Create a paragraph node. Create a text node with content of your choosing. Add it to the paragraph node. Insert it before a node represented by a variable of your choosing, under a parent represented by a variable of your choosing.

document.createElement("DIV");

Create a simple DOM DIV

<input type="text" id="age">

Create a text field with the id "age"

var newText = document.createTextNode("Bada-bing");

Create a text node with the string "Bada-bing" and assign it to the variable newText, which hasn't been declared beforehand.

var newE = document.createElement("a"); newE.setAttribute("href", "http://www.bees.com"); parentElement.insertBefore(newE, existingE);

Create an <a> node. Make it link to "bees.com". Insert it before a node represented by a variable of your choosing, under a parent represented by a variable of your choosing.

history.go(2);

Direct the browser to skip 2 URLs ahead. )

pop.document.write("<p>Whee!</p>");

Display a paragraph with text content "Whee!" in a window that's already open, whose handle is pop.

<input type="text" onFocus="this.style.backgroundColor = 'yellow';">

Display a text field. When the user clicks in the field, the field turns yellow.

hi.document.write("<h1>Hello world!</h1>");

Fill a window whose handle is hi with an h1 head that says "Hello world!"

document

Fill in the blank var nameEntered = ________.getElementById("nameField").value;

attributes

Fill in the blank to make a collection of attributes and assign it to attList. var attList = targetNode.___________;

childNodes

Fill in the blank to make a collection of the nodes one level below the node represented by pNode. var nodeList = pNode.______;

Math.ceil

Fill in the blank to round up. var roundedNum = ___________(fractionalNum);

Hello

Fill in the blank. The value of the first child of the first element is "______" <p>Hello<strong> world!</strong></p>

var segIndex = text.indexOf("x");

Find the index of the first character of the first instance of a literal string segment in a string represented by a variable, and assign it to another variable, which hasn't been declared beforehand.

var segIndex = text.lastIndexOf("x");

Find the index of the first character of the last instance of a literal string segment in a string represented by a variable, and assign it to another variable, which hasn't been declared beforehand.

var foo = p.childNodes.length;

Find the number of children of a parent represented by the variable p and assign it to a variable that hasn't been declared beforehand.

var numChildren = p.childNodes.length;

Find the number of children of a parent represented by the variable p and assign it to a variable that hasn't been declared beforehand.

var cells = t.getElementsByTagName("td");

Get a list of the regular (non-header) cells in a table that has been assigned to the variable t. Assign the list of items to the variable cells, which hasn't been declared beforehand.

var nam = target.attributes[1].nodeName;

Get the name of the second attribute of an element that has been assigned to a variable of your choosing, and assign the name to another variable of your choosing, which hasn't been declared beforehand.

var nType = tNode.nodeType;

Get the node type of the node assigned to the variable tNode and assign it to the variable nType, which hasn't been declared beforehand.

var pgraphText = d.childNodes[1].innerHTML;

Get the text content of the second child of the div represented by the variable d and assign it to the variable pgraphText, which hasn't been declared beforehand

var nodeVal = tNode.nodeValue;

Get the value of the text node assigned to the variable tNode and assign it to the variable nodeVal, which hasn't been declared beforehand.

pic1.setAttribute("src", "next-image.png");

Give an image that has been assigned to the variable pic1 a new source, next-image.png, by manipulating an attribute.

var a = ['how', 'now', 'brown', 'cow', 'farm', 'animals' ]; filterBy = 'ow' filterBy ? a.filter((a) => a.indexOf(filterBy) !== -1) : a;

Given an array var animals = ['dog', 'cat', 'cow', 'moose', 'duck', 'crow' ]; create a function that returns an array of elements that is filtered by an input parameter for example ... if the function receives 'ow', it will return ['cow','crow']

scope

Global and local variables differ in their _______.

Parent, child, siblings 1st child of, 2nd child of and so on

How do we specify node relationships to other nodes?

3

How many element nodes do you see in this markup? (Answer with a numeral.) <div> <h3>Age-old problem</h3> <p> So many nodes, so little time. </p> </div>

dogs = dogs.splice(2, 1, "dachshund");

How would you add "dachshund" to the 3rd element of the following array while removing "Bob"? var dogs = ["Hound", "Lab", "Bob", "Great Dane"];

foo.push(2, 3, 5);

How would you add 3 numbers to the end of an array?

var theProps = []; for (var prop in dog) { theProps.push(prop); }

How would you assemble an array of properties (theProps) for an object named dog?

ID

If I plan to validate this field, targeting it in the most common way, what's missing? Answer with one word, in upper-case. <input type="text">

return <form onSubmit="return validateMe();">

If I plan to validate this form, what's missing from this markup? <form onSubmit="validateMe();">

1

If a function has 3 parameters, how many values can be returned to the calling code? Answer with a numeral.

3 2 text nodes plus the <em> element

If the children of the paragraph are assigned to kids, what is the value of kids.length? (Answer with a numeral.) <p>This is <em>very</em> important!</p>

if (e.hasAttribute("class") === false) { e.setAttribute("class", "misc"); }

If the element assigned to the variable e doesn't have a class, set its class to "misc".

3

If the node is a text node, what is the value of nType? var nType = targetNode.nodeType;

1

If the node is an element node, what is the value of nType? var nType = targetNode.nodeType;

if (married === false) { document.getElementById("status").value = "available"; }

If the variable married is false, place the value "available" in the field with the id "status"

yes

If you have an empty array defined in line 1 like so: var foo = []; is it legal to say this? foo[3] = "hello";

//g

If you want all instances replaced, enter 3 characters that need to appear in this statement. var y = x.replace("a", "z");

document.getElementById("lnk").onclick = doIt;

In a single statement convert this markup to scripted event-handling. <a href="JavaScript:void(0)" onClick="doIt()" id="lnk">Click</a>

document.getElementById("b1").onclick = sayHi;

In a single statement convert this markup to scripted event-handling. <input type="button" value="Click to be greeted" id="b1" onClick="sayHi();">

var child2 = document.getElementById("d2").childNodes[1].nodeName;

In a single statement get the name of the second child of an element with the id "d2" and assign it to the variable child2, which hasn't been declared beforehand.

var numAtts = document.getElementById("pic29").attributes.length;

In a single statement get the number of attributes of an element with the id "pic29" and assign the number to the variable numAtts, which hasn't been declared beforehand.

pNode.insertBefore(newE, pNode.childNodes[2]);

In a single statement insert a new element represented by newE before the third child of the parent pNode.

variable

In one word, what is a flag?

onclick note the value returns all lower case.

Look at the following markup and the code that follows it, and tell me the value of nam. Include the quotation marks. <p id="p1" class="regular" onClick="disappear();"> var nam = document.getElementById("p1"). attributes[2].nodeName;

onchange - An HTML element has been changed onclick - The user clicks an HTML element onmouseover - The user moves the mouse over an HTML element <span onmouseover="this.style.color='red'">Mouse over me!</span> onmouseout - The user moves the mouse away from an HTML element onkeydown - The user pushes a keyboard key onload - The browser has finished loading the page

Name 5 HTML events - and basic example of how javascript can handle those events

case sensitive officially named ECMA Script its the language of the browser - much like VBA and macros were/are the language of MS Word, etc Acts on the DOM (browser's representation of page)

Name at least 3 characteristics of javascript

• global vars at top • functions together • local vars at top of function • Variable and function names written as camelCase • Global variables written in UPPERCASE (We don't, but it's quite common) • Constants (like PI) written in UPPERCASE //see http://www.w3schools.com/js/js_conventions.asp

Name at least 5 generally accepted javascript coding conventions...

var foo = window.open(); foo.close();

Open a blank window, then close it.

var foo = document.write("hello.html");

Open a document, loading an html file that shares the same host and subdirectory as the original document.

var popup = window.open("offer.html");

Open a new window on the current site whose handle is popup and whose document is offer.html.

var w = window.open("", "", "width=300,height=200,left=100,top=50");

Open a new window, newWin, with a blank URL and name, and parameters for (in this order) size across, size up and down, distance from the side, and distance from the top. The parameters are 300, 200, 100, and 50.

var pop = window.open(newDocument);

Open a window, loading a document that's represented by a variable.

nodes

People are the units of a company organization chart. What are the units of the DOM?

document.getElementById(storedId).innerHTML = "212";

Place a text value in a paragraph whose id is stored in a variable. Make up the variable

document.getElementById("p1").innerHTML = document. getElementById("field1").value;

Place the value found in a field into a paragraph. Make up the ids.

<img src="but.gif"

The code displays an image, but.gif, that, when clicked, calls the function myFunc. Fill in the blank. _______________ onClick="myFunc();">

parentNode.removeChild(badNode);

Remove a node represented by a variable of your choosing from a parent represented by another variable of your choosing.

<p >Hello world!</p >

Revise this markup to eliminate whitespace but keep on 3 lines (in the markup) <p> Hello world! </p>

this.addTaxTo = function(price) {

Rewrite this line so it'll work in a constructor function. addTaxTo: function(price) {

this.doSomething = function() {

Rewrite this snippet so that it can be used for a constructor function. doSomething: function() {

var foo = Math.floor(.5);

Round .5 to 0 and assign it to a variable that hasn't been declared beforehand.

text

Some browsers interpret whitespace in markup as nodes. What type of nodes are they?

replace

The current page is to be excluded from the browser history when the new page loads. Fill in the blank. window.location._______("http://www.wow.com");

assign

The current page is to be included in the browser history when the new page loads. Fill in the blank. window.location._______("http://www.wow.com");

var pClass = pgraph.className;

The element has been assigned to the variable pgraph. Assign its class to the variable pClass, which hasn't been declared beforehand.

alert(d.getFullYear());

The Date object is represented by d. Code a statement that displays the year in an alert.

if (now.getMonth() > 8) {

The Date object is represented by now. Code the first line of an if statement that tests whether it's the last quarter of the year

page1.html

The browser is on page1.html. There is no history. The statement history.go(-1)executes. What page does the browser land on?

+=

The class "formal" is added to any existing classes assigned to the element. Fill in the blank. document.getElementById("paragraph1").className __ " formal";

value="Click"

The code creates a button that says "Click". Fill in the blank. <input type="button" _________ onClick="myFunc();">

<input type="button"

The code creates a button that, when clicked, calls a function. Fill in the blank. _____________ value="Submit" onClick="myFunc();">

this.

The method definition in a constructor has three features that a one-off literal definition doesn't have. Two of them are = in the definition and ; after the closing curly bracket. What is the third feature? (5 characters)

lot31.size;

The object is lot31. One of its properties is size. How do you refer to the property in code?

case

The second keyword used in a switch statement is _______.

var bigHeads = document.getElementsByTagName("h1");

The statement assigns a collection of h1 headings in a document to the variable bigHeads, which hasn't been declared beforehand. Code it.

imgLst[0];

The statement assigns the first item of imgLst to firstPic. Fill in the blank. var firstPic = __________

length

The statement assigns the number of elements in the array to the variable. Fill in the blank. var num = myStr.________;

node2

The statement inserts the node represented by cNode before the child represented by node2. The parent node is represented by pNode. Fill in the blank. pNode.insertBefore(cNode, _______);

.getElementsByTagName

The statement makes a collection of all the divs in the document. Fill in the blank. var divs = document______________("div");

Setting the value is normally used for input/form elements. innerHTML is normally used for div, span, td and similar elements.

Under what conditions do you use getElementById("foo").value = "hello"; vs the innerHTML property?

window.location.assign("http://www.me.com");

Using assign, direct the browser to me.com.

<a href="JavaScript:void(0)" onClick="alert('Hi');">Click</a>

Using the approach (no #) that prevents page from scrolling to top of page, code a link that triggers an alert that says "Hi" when a link that says "Click" is clicked.

pNode.insertBefore(newOne, existing.nextSibling);

Using variables of your choosing, insert a new node after an existing node that has been targeted and assigned to a variable.

""

What 2 characters are missing? var isPropertyOf = size in thing;

doSomething

When the button represented by b1 is clicked, the function doSomething is called. Fill in the blank. b1.onclick = ________; Note: use pure javascript not html

onclick

When the button represented by b1 is clicked, the function is called. Fill in the blank. b1.______ = doSomething;

node2.nextSibling

When the following statement executes, what node comes before cNode? pNode.insertBefore(cNode, node2.nextSibling);

<img src="click.png" onClick="alert('You clicked the pic');">

When the image click.png is clicked, an alert displays saying, "You clicked the pic" Code it.

some browsers treat it as text nodes.

Why is it important to be aware of white space in the markup?

4, string.length;

You want to take a slice out of the string that starts at the fifth character and goes to the end. Fill in the blank. var segment = someWord.slice(___);

:00:00

You're creating a Date object for noon on the dot. Fill in the blank. var prev = new Date("January 1, 2000 _______");

onSubmit

for elements that belong to forms, what is the keyword that typically calls a function to validate?

ConstructorFunctionName.Prototype.NameOfSharedFunction Person.prototype.calcAge = function() { //code here };

how do we create a new prototype

document.write("<h1>my new page</h1>");

how do you replace all the nodes of a html page in one fell swoop?

2

how many times will the if statement execute? for (var i = 0; i < 10; i++) { if (i === 1) { alert(i); break; } }

var airlines = [];

how would you create an empty array?

"www.google.com"

http://www.google.com/microsoft Look at the URL shown above and tell me the value of currentSite. It's a string, so enclose it in quotes. var currentSite = window.location.hostname;

"#2"

http://www.microsoft.com/default.html#2 Look at the URL shown above and tell me the value of pageSection. It's a string, so enclose it in quotes. var pageSection = window.location.hash;

document element text

name at least 3 types of nodes in the DOM

break;

switch statement: What statement keeps all the statements below the true case from executing?

adddlert is not defined

try and catch what will this code return? try { adddlert("Welcome guest!"); } catch(err) { document.getElementById("demo").innerHTML = err.message; }

document.getElementById("foo").value = "3";

using javascript (not HTML) put a value in a text field with an id of foo

God.

var body = document.getElementsByTagName("body"); var b = body[0]; what is the value of: b.childNodes[1].childNodes[2].innerHTML <div id="d1"> <p>Don't tell me.</p> <p>Let me guess.</p> </div> <div id="d2"> <p>Oh.</p> <p>my.</p> <p>God.</p> </div>

foo = foo.replace(/my house/g, "our house");

var foo = "my house in the middle of the street"; write a statement that changes all occurrences of "my house" to "our house"

3

var text = "To be or not to be."; var indx = text.indexOf("be"); What is the value of indx?

remember slice creates a copy - doesnt change the arrray slice(arg1, arg2); arg1 = where to start index arg2 = where to finish index + 1

what are the arguments to pass in the slice function

splice(arg1, arg2, arg3); arg1 = where to start index arg2 = how many to delete arg3 = what to add (can be array)

what are the arguments you pass in the splice function?

Assign value of x to what is in y

what does x = y mean

option value select element inside a form <form onsubmit="return checkForSelection();"> <select id="states"> <!--<option value ="" selected ="selected"> SELECT A STATE </option> --> <option value="AL"> Alabama </option> <option value="AK"> Alaska </option> <option value="AZ"> Arizona </option> <option value="AR"> Arkansas </option> </select> <input type="submit" value="Submit Form"> </form>

when collecting values via dropdown, what html elements do we use?

handle

what do you call the item on the left of equals sign? var foo = window.open();

this is like hitting the back button. goes back 1

what does this code do? window.history.go(-1);

-1

what does this return for the value of bar? var foo = "monkey, gibby, willow, clancy, boone"; var bar = foo.indexOf("44"); console.log(bar);

x is equal to and equal type of y

what does x === y mean?

a way to share a method or property across multiple objects

what is a prototype?

space - window names (second parameter) cant have spaces.

what is the illegal character here? var newWin = window.open("", "My Window");

.getAttribute('name')

what is the javaScript syntax to get an attribute of a node? A. .attr('name') B. .getAttribute('name')

camel case myMethodName

what is the naming convention for javascript methods

they are handy when we need a template for creating objects.

what is the purpose of a constructor function?

get the element and define its event with lowercase - otherwise wont work.

what is the rule when defining the event with code rather than the in-line approach? eg in-line = <input type="button" id="btn1" onClick="doThis();">

B. attributes

what is the syntax for getting all the attributes of a given node? A. getAttribute B. attributes

if (condition) { block of code to be executed if the condition is true }

what is the syntax for if statement

< script src =" whatever.js" > </ script >

what is the syntax for including an external javascript file?

th

what is the tag name of a header cell in an html table?

slice slice(index of element to begin copy, index of element to end copy + 1)

what keyword can be used to copy elements of an array to another

nodeName

what keyword do we use to determine if a node is a link, button, image, etc?

dNode.hasAttribue("attributeName");

what keyword do we use to find whether a DOM node has an attribute of one kind or another?

in

what keyword is used to determine if an object has a property?

prompt example: var userInput = prompt("what is your favorite color"); console.log(userInput); its ok to say window.prompt

whats the keyword to get info from user?

Direct the browser to wow.com. Exclude the current page from the browser history.

window.location.replace("http://"www.wow.com");

var theDate = new Date();

write a statement that declares and creates a new date object (remember case sensitive)

f1.onsubmit = myFunction;

you have a form element f1. write a click event to call a function

document.getElementById("paragraph1").className += " formal"; where there is a space between the quote and formal ... " formal" .. not "formal"

Enter what's missing here. document.getElementById("paragraph1").className += "formal";

var att1 = document.getElementById("e").attributes[0].nodeName;

In a single statement, assign the name of the first attribute of an element with the id "e" to the variable att1, which hasn't been declared beforehand.

document.getElementById("p3").setAttribute("class", "special");

In a single statement, assign to an element with the id "p3" the class "special".

parentNode.removeChild(parentNode.lastChild);

In a single statement, eliminate the last node one level down from the element represented by parentNode.

var ad = document.getElementById("info").getAttribute("href");

In a single statement, find out the address of a link whose id is "info" and assign it to the variable ad, which hasn't been declared beforehand.

var list = document.getElementById("p3").childNodes;

In a single statement, make a collection of nodes one level down from an element with the id "p3". Assign the collection to a variable, list, which hasn't been declared beforehand.

str = str.replace(/foo/g, "bar");

In a string represented by a variable replace all instances of one string with another and assign the revised string to the original variable.

()

In addition to history, a dot, and a semicolon at the end, there are 2 characters that are always part of a statement that moves the browser backward and forward. Type the characters in the order in which they appear.

function

In one word, what is a block of code that executes whenever you invoke its name?

document

In one word, what is the top level of the DOM?

pixels

In size and position parameters, what do the numbers represent? Answer with one word.

#IMG

In the markup below what is the node name of the element? (Pay attention to the case.) <img src="http://www.wikipedia.org">

IMG

In the markup below what is the node name of the element? (Pay attention to the case.) <img src="http://www.wikipedia.org">

onClick="myFunc();">

The code creates a button that, when clicked, calls the function myFunc. Fill in the blank. <input type="button" value="Click" ______________

contentDiv

The statement makes a collection of all the paragraphs in the div represented by the variable contentDiv and assigns the collection to pgraphs. Fill in the blank. var pgraphs = ________getElementsByTagName("p");

reload

The statement refreshes the current webpage. Fill in the blank. window.location.________();

()

The statement will round the number to an integer. Fill in the blank. var newNum = oldNum.toFixed___;

.childNode[0]; or .firstChild;

The target is the first child of the body, which has been assigned to the variable b. Fill in the blank. var e = b_________________

b.childNodes[1].childNodes[3];

The target is the fourth child of the second child of the body. The body has been assigned to the variable b. Fill in the blank. var e = _________________________

undefined variables

The try...catch approach is mainly useful for spotting ________. Answer with two words.

parameters

The variables in a function definition that catch the data passed to them by the calling code are called _________.

function() {

This is the first line of a prototype statement that creates a prototype method for the constructor Product. The method has no parameters. Fill in the blank. Product.prototype.totalCosts = _____________

if (targetField.value.length === 0) { alert("Please enter something"); return false; }

This is the first line of code that displays an alert if the field is empty, and cancels the form submission. Write 4 more lines to complete it. var targetField = document.getElementById("f1");

using the working down notion.... var dTitle = document.firstChild.firstChild.firstChild. firstChild.nodeValue; or var dTitle = document.childNodes[0].childNodes[0].childNodes[0]. childNodes[0].nodeValue; var dTitle = document.head.childNodes[0];

Working your way down the DOM hierarchy, get the value of the document's title text and assign it to the variable dTitle, which hasn't been declared beforehand. (In this document the title is the first child of the head.)

function person(first, last, age, eye) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; } var myFather = new person("John", "Doe", 50, "blue"); var myMother = new person("Sally", "Rally", 48, "green");

Write a constructor function for a person

for (var i = 0; i < p.childNodes.length; i++) if (p.childNodes[i].nodeType === 1) { break } }

Write a for loop that checks to see if the next child of a parent represented by a variable p is an element node. If it is, break out of the loop. Begin by assigning the number of children of the parent to a variable, which hasn't been declared beforehand. Use the variable to limit the number of loops. Use the most common loop specifications.

hello();

Write a function call. Name it anything you like,

function foo() { foo(); }

Write a function that calls itself

<form onSubmit="chkForm();">

Write an opening form tag. When the form is submitted, the function chkForm is called.

<form onSubmit="myFunc('myField');">

Write an opening tag for a form. When the form is submitted, a function is called. The id of a field is passed to the function. Make up the id.

parseInt("1.5");

Write the code to convert "1.5" to 1?

if (document.getElementById("pet").value === "dog") {

Write the first line of an if statement. If what's in the field with the id of "pet" is "dog"....

<img src="ford.jpg" id="car" onClick="swap(id, 'bmw.jpg');">

Write the markup for an image with the source "ford.jpg" and the id "car". When the user clicks on it, a function, swap, is called. The markup passes the id and the image to insert, "bmw.jpg" as arguments, in that order. Write in this order: source, id, event handler.

<form onSubmit="return validate();">

Write the opening tag for a form that executes a validation function, validate, when the form is submitted

pets = pets.slice(3, 5);

var pets = ["dog", "cat", "ox", "duck", "frog", "flea"]; Reduce it to "duck" and "frog" using slice.

pets = pets.splice(1, 3, "bear", "horse");

var pets = ["dog", "cat", "ox", "duck", "frog"]; Add 2 elements after "dog" and remove "cat", "ox", and "duck".

pets = pets.slice(3, 5);

var pets = ["dog", "cat", "ox", "duck", "frog"]; Reduce it to "duck" and "frog" using slice.

pets = pets.splice(1, 2);

var pets = ["dog", "cat", "ox", "duck", "frog"]; Remove "cat" and "ox".


संबंधित स्टडी सेट्स

Pharm Ad Chronic Disease, Pain, and Disability

View Set

CHEMISTRY - UNIT 2: STARTING THE INVESTIGATION: HOW TO IDENTIFY ELEMENTS, COMPOUNDS, AND MIXTURES USING CHEMICAL AND PHYSICAL PROPERTIES TO IDENTIFY SUBSTANCES (11th grade)

View Set

Chapter 2: Build-in Data Types for Programming? Part 2

View Set