0% found this document useful (0 votes)
21 views163 pages

JavaScript Cookbook PDF

Uploaded by

924957
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views163 pages

JavaScript Cookbook PDF

Uploaded by

924957
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 163

JavaScript Cookbook PDF

Shelley Powers

Scan to Download
JavaScript Cookbook
Essential Code Recipes for Efficient JavaScript
Development and Web Applications
Written by Bookey
Check more about JavaScript Cookbook Summary
Listen JavaScript Cookbook Audiobook

Scan to Download
About the book
Unlock the full potential of JavaScript with this
comprehensive cookbook, designed to streamline your
programming process. Filled with practical code recipes for
common tasks, this guide empowers you to build robust web
applications that function seamlessly across all browsers.
Simply copy and paste the provided code snippets to expedite
your projects while deepening your understanding of
JavaScript. Explore the latest advancements in ECMAScript 6,
leverage powerful libraries like Node and Underscore, and
delve into popular MVC frameworks such as Angular, Ember,
and Backbone. Learn to create interactive web and desktop
applications, utilize Scalable Vector Graphics (SVG) and
canvas elements, write server-side JavaScript with Node.js,
facilitate client-server communication using sockets, and
harness advanced Web APIs for mobile devices. Discover the
tools you need to elevate your JavaScript skills and enhance
your development workflow.

Scan to Download
About the author
Shelley Powers is a seasoned web developer and author with a
wealth of experience in JavaScript and web technologies,
making her a notable figure in the programming community.
With a strong background in writing and teaching, she has
contributed to numerous publications and online platforms,
sharing her expertise to help developers of all skill levels
master JavaScript and its intricacies. Powers is known for her
practical approach to programming, emphasizing clear
explanations and hands-on examples that empower readers to
tackle real-world challenges. Her work not only reflects her
technical knowledge but also her commitment to fostering a
deeper understanding of web development among her
audience.

Scan to Download
Summary Content List
Chapter 1 : 1.1. Using Errors

Chapter 2 : 1.2. Capturing Errors by their subtypes

Chapter 3 : 1.3. Throwing useful errors

Chapter 4 : 1.4. Throwing custom errors

Chapter 5 : 1.5. Handling JSON parsing errors

Chapter 6 : 2.1. Accessing a Given Element and Finding Its

Parent and Child Elements

Chapter 7 : 2.2. Traversing the Results from

querySelectorAll() with forEach()

Chapter 8 : 2.3. Adding Up Values in an HTML Table

Chapter 9 : 2.4. Problem

Chapter 10 : 2.5. Finding All Elements That Share an

Attribute

Chapter 11 : 2.6. Accessing All Images in a Page

Chapter 12 : 2.7. Discovering All Images in Articles Using

the Selectors API

Scan to Download
Chapter 13 : 2.8. Setting an Element’s Style Attribute

Chapter 14 : 2.9. Inserting a New Paragraph

Scan to Download
Chapter 1 Summary : 1.1. Using Errors

Section Summary

1.1 Using JavaScript features an Error type and seven subtypes, providing properties like constructor, name, and
Errors message. Errors can be instantiated, thrown, and caught in a try-catch block, with standardized messages
recommended for consistent reporting.

1.2 Capturing JavaScript's Error subtypes include EvalError, InternalError, RangeError, ReferenceError, SyntaxError,
Errors by their TypeError, and URIError. Use instanceof in catch blocks to capture specific subtypes, though only one catch
Subtypes block is allowed, complicating error handling.

1.3 Throwing Use TypeError for incorrect variable types and RangeError for unacceptable values. Provide informative
Useful Errors messages when throwing errors, and avoid using errors for validating user inputs to maintain a good user
experience.

1.4 Throwing Create custom error types by subclassing the Error class in ECMAScript 2015. Set the error name, capture
Custom Errors the stack trace, and ensure clarity of the subclass API. Additional properties can be added for enriched
information.

1.5 Handling JSON parsing can raise SyntaxErrors for malformed data. Create a custom SyntaxError subtype for JSON
JSON Parsing parsing and use a helper function to catch and repackage these errors as a JSONParseError for improved
Errors logging and management.

1.1 Using Errors

JavaScript has a parent Error type and seven subtypes. Errors


provide three main properties: constructor, name, and

Scan to Download
message. To create and handle errors, instantiate an Error or
its subtype, throw it, and catch it with a try-catch block. For
consistent error reporting, keep a list of standardized error
messages. Errors can be created using the new keyword or
directly calling Error().

1.2 Capturing Errors by their Subtypes

JavaScript's Error subtypes include EvalError, InternalError,


RangeError, ReferenceError, SyntaxError, TypeError, and
URIError. To catch errors by subtype, use the instanceof
operator in the catch block. Responding to specific error
subtypes can offer more context on issues in the code.
However, JavaScript allows only one catch block, which
makes error handling more complicated.

1.3 Throwing Useful Errors

Use TypeError to indicate incorrect variable types and


RangeError for values outside an acceptable range. When
throwing these errors, provide informative messages about
the values involved. Avoid using errors for user input
validation, as they can disrupt user experience.

Scan to Download
1.4 Throwing Custom Errors

You can create custom error types by subclassing the Error


class using ECMAScript 2015 syntax. This involves setting
the name of the error, capturing the stack trace, and ensuring
the subclass API remains understandable. Custom properties
can be added for additional information.

1.5 Handling JSON Parsing Errors

JSON parsing can lead to SyntaxErrors when encountering


malformed data. To improve error handling, create a custom
subtype of SyntaxError specifically for JSON parsing. A
helper function can be used to catch SyntaxErrors and
repackage them as the new JSONParseError type for better
logging and error management.

Scan to Download
Example
Key Point:Utilizing JavaScript's Error Management
Effectively
Example:Imagine you are coding a web application and
encounter user input that doesn't match expected types.
Instead of letting the application crash, you can employ
JavaScript's error handling by creating a TypeError. By
instantiating this error, you provide a clear and
informative message that highlights the specific nature
of the problem. For example, you might throw a new
TypeError('Expected a string but received a number');
this allows you to catch this specific error in a try-catch
block. When users face an error, they receive guidance
on how to correct their input, significantly enhancing
the user experience.

Scan to Download
Critical Thinking
Key Point:The necessity and complexity of
specialized error handling in JavaScript.
Critical Interpretation:One key point highlighted in this
chapter is the importance of understanding JavaScript's
error handling mechanisms, particularly its subtypes.
The author suggests that responding to specific error
types can provide deeper insights into code issues;
however, this approach is complicated due to the
limitation of a single catch block. While this viewpoint
emphasizes the value of tailored error management, it
could also be critiqued for potentially overcomplicating
error handling, especially in simpler applications where
a uniform error strategy might suffice. Alternatives can
be found in various programming paradigms that
advocate for less granular error management
(Crockford, D. (2008). 'JavaScript: The Good Parts').
Thus, while Powers provides a comprehensive
overview, readers should weigh the practical
implications of error specificity against its complexity.

Scan to Download
Chapter 2 Summary : 1.2. Capturing
Errors by their subtypes

Capturing Errors by Their Subtypes

JavaScript features seven subtypes of Error that can help


identify the nature of an error in code, potentially leading to
recovery or providing insight into the issue:
-
EvalError
: Triggered by the use of `eval()`.
-
InternalError
: Specific to the JavaScript engine, not part of the
ECMAScript standard.

Scan to Download
-
RangeError
: Indicates a value is outside its valid range.
-
ReferenceError
: Raised for issues when dereferencing an invalid reference.
-
SyntaxError
: Related to syntax problems in the code, including JSON.
-
TypeError
: Occurs when a variable or parameter is the wrong type.
-
URIError
: Raised by issues with `encodeURI()` and `decodeURI()`.

Identifying Subtypes in Error Handling

To catch errors by subtype, the following approach is


suggested:
```javascript
try {
// Some code that may cause an error
} catch (err) {

Scan to Download
if (err instanceof RangeError) {
// Handle RangeError
} else if (err instanceof TypeError) {
// Handle TypeError
} else {
// Rethrow any other errors
throw err;
}
}
```

Discussion on Error Handling

Handling errors based on subtype can provide useful


information about code issues. However, JavaScript allows
only one catch block, necessitating manual type checking
using `instanceof`. It’s crucial to implement full if-else
statements to avoid unintentionally suppressing errors. Some
errors, like `EvalError` or `ReferenceError`, may not be
recoverable, highlighting the importance of informative error
reporting rather than trying to restore a functional state.

Throwing Useful Errors

Scan to Download
Two Error subtypes that can effectively communicate states
in applications are `TypeError` and `RangeError`:
-
TypeError
: Demonstrates incorrect types for parameters or variables.
-
RangeError
: Indicates a value or parameter is out of a specified range.
Example usage:
```javascript
function calculateValue(x) {
if (typeof x !== 'number') {
throw new TypeError(`Value [${x}] is not a number.`);
}
}
function setAge(age) {
const upper = 125;
const lower = 18;
if (age > 125 || age < 18) {
throw new RangeError(`Age [${age}] is out of the
acceptable range.`);
}
}
```

Scan to Download
Error messages should be clear and inclusive of both the
erroneous value and expectations.

Creating Custom Error Types

In situations where existing Error types do not suffice, one


may create custom error types through subclassing:
```javascript
class CustomError extends Error {
constructor(customProp = 'customValue', ...params) {
super(...params);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CustomError);
}
this.name = 'CustomError';
this.customProp = customProp;
}
}
```
When subclassing, maintain familiarity for later developers
and include meaningful custom properties while adhering to
expected error behavior.

Handling JSON Parsing Errors

Scan to Download
JSON parsing can lead to `SyntaxError` on encountering
malformed data. To enhance error handling:
- Create a `JSONParseError` subclass of `SyntaxError` to
specify JSON parsing issues.
Example function:
```javascript
class JSONParseError extends SyntaxError {
constructor(...params) {
super(...params);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, JSONParseError);
}
this.name = 'JSONParseError';
}
}
function betterParse(jsonString) {
try {
JSON.parse(jsonString);
} catch (err) {
if (err instanceof SyntaxError) {
throw new JSONParseError(err);
} else {
throw err;

Scan to Download
}
}
}
```
This approach ensures more specific error logging while
maintaining general error handling for other exceptions.

Scan to Download
Chapter 3 Summary : 1.3. Throwing
useful errors
Section Details

Throwing Useful Errors

Overview of Error Subtypes JavaScript has various Error subtypes; TypeError and RangeError are especially useful.

Using TypeError Ideal for signaling incorrect parameter types. Example provided.

Using RangeError Notifies when values are out of acceptable ranges. Example provided.

Guidelines for Error Messages Make messages informative, avoid using errors for user input validation.

Throwing Custom Errors

Creating Custom Error Developers can create their own subtypes when standard types are inadequate. Example
Subtypes provided.

Best Practices for Subclassing Avoid complexity, ensure ease of use, and follow constructor guidelines.
Error

Handling JSON Parsing Errors

Challenges with JSON Parsing SyntaxErrors may occur from malformed JSON, creating lack of specificity in errors.

Solution with Custom Error Create a custom subclass of SyntaxError for effective handling of JSON parsing errors.
Example provided.

Benefits of Custom Error Specific JSONParseError enhances logging and allows targeted error management.
Handling

Throwing Useful Errors

Overview of Error Subtypes

JavaScript has several Error subtypes, but TypeError and


RangeError are particularly useful. They help express

Scan to Download
incorrect states within applications.

Using TypeError

The TypeError is ideal for signaling incorrect parameter


types.
Example:
```javascript
function calculateValue(x) {
if (typeof x !== 'number') {
throw new TypeError(`Value [${x}] is not a number.`);
}
// Rest of the function
}
```

Using RangeError

The RangeError is suitable for notifying when values are out


of acceptable ranges.
Example:
Install Bookey App to Unlock Full Text and
```javascript
function setAge(age) { Audio
const upper = 125;

Scan to Download
Chapter 4 Summary : 1.4. Throwing
custom errors

Throwing Custom Errors

Problem

Creating custom error types in JavaScript can be necessary


when the built-in Error type is too broad or specific.

Solution

Subclass the Error types using ECMAScript 2015 class


syntax:
```javascript
class CustomError extends Error {
constructor(customProp='customValue', ...params) {
super(...params);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CustomError);
}

Scan to Download
this.name = 'CustomError';
this.customProp = customProp;
}
}
```

Discussion

When creating custom error subclasses, consider:


- Maintaining compatibility with standard JavaScript error
handling.
- Providing sufficient information without over-complicating
the API.
Key points to remember:
- Avoid replicating errors from other languages.
- Ensure that custom error properties are distinct from
standard error message arguments.
- Handle the stack trace correctly for V8 engines by checking
for `Error.captureStackTrace`.
---

Handling JSON Parsing Errors

Scan to Download
Problem

Parsing JSON can lead to various errors, primarily throwing


SyntaxErrors which lack detail.

Solution

Create a custom error type for JSON parsing:


```javascript
class JSONParseError extends SyntaxError {
constructor(...params) {
super(...params);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, JSONParseError);
}
this.name = 'JSONParseError';
}
}
function betterParse(jsonString) {
try {
JSON.parse(jsonString);
} catch (err) {
if (err instanceof SyntaxError) {
throw new JSONParseError(err);

Scan to Download
} else {
throw err;
}
}
}
```

Discussion

To improve error logging and handling when JSON parsing


fails:
- Use the `betterParse` function to handle JSON strings, catch
SyntaxErrors, and repackage them as JSONParseErrors.
- This method allows for more precise error handling,
making it easier for developers to troubleshoot JSON-related
issues.

Scan to Download
Example
Key Point:Understanding error handling in
JavaScript through custom exceptions makes
debugging more efficient.
Example:Imagine you are debugging an application that
parses user inputs as JSON. When a malformed JSON
string is encountered, the default SyntaxError doesn't
provide enough context, leaving you puzzled about the
problem's origin. By implementing a custom error called
JSONParseError, you ensure that whenever JSON
parsing fails, it throws a descriptive error with your
custom properties. This tailored error not only captures
the stack trace but delivers specific information about
the failure, enhancing your ability to quickly identify
and resolve issues during development.

Scan to Download
Critical Thinking
Key Point:Custom error handling is crucial in
JavaScript programming.
Critical Interpretation:The author suggests creating
custom error types to enhance error reporting and
debugging capabilities, particularly for scenarios like
JSON parsing where standard errors can be ambiguous.
However, custom error handling practices may vary
depending on project needs and contexts, and the
effectiveness of these custom classes can be debated. A
viewpoint not often discussed is that excessive
customizations can lead to over-engineering,
diminishing the simplicity and clarity that JavaScript is
known for. As noted by David Flanagan in 'JavaScript:
The Definitive Guide,' balancing the use of custom
errors with the intrinsic capabilities of JavaScript error
handling is important. While custom errors can enhance
clarity, they could also introduce unnecessary
complexity or confusion if not implemented
thoughtfully.

Scan to Download
Chapter 5 Summary : 1.5. Handling
JSON parsing errors
Section Content

Overview JSON is a popular data format in JavaScript. JSON processing involves `JSON.stringify` for converting
JavaScript objects to JSON and `JSON.parse` for deserializing JSON strings. While stringifying is error-free,
parsing can encounter issues like malformed JSON.

Problem Parsing malformed JSON can result in a generic `SyntaxError`, which does not specify the issue.

Solution A custom error type, `JSONParseError`, extends `SyntaxError` to offer clearer error handling. The `betterParse`
function attempts to parse JSON and throws `JSONParseError` for parsing issues.

Discussion This method improves error handling by allowing checks for `JSONParseError`. The `betterParse` function
enhances clarity in logging errors during JSON parsing.

Handling JSON Parsing Errors

Overview

JavaScript Object Notation (JSON) is a widely used data


format thanks to JavaScript's popularity. Two native
functions aid in JSON processing: `JSON.stringify(jsObject)`
for JavaScript-to-JSON conversion and
`JSON.parse(jsonString)` for deserializing a JSON string into
a JavaScript object. While stringifying JavaScript typically
doesn’t cause errors, parsing JSON can lead to various
problems, such as malformed JSON or non-JSON inputs.

Scan to Download
Problem

Parsing bad or malformed JSON can raise generic


`SyntaxError`, which lacks specificity regarding the
underlying issue.

Solution

To address this, a custom error type, `JSONParseError`,


extends the `SyntaxError` to provide clearer logging and
error handling.
```javascript
class JSONParseError extends SyntaxError {
constructor(...params) {
super(...params);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, JSONParseError);
}
this.name = 'JSONParseError';
}
}
function betterParse(jsonString) {
try {

Scan to Download
return JSON.parse(jsonString);
} catch (err) {
if (err instanceof SyntaxError) {
throw new JSONParseError(err);
} else {
throw err;
}
}
}
```

Discussion

This method enhances error handling when parsing JSON by


allowing consumers to check specifically for
`JSONParseError` instead of the broader `SyntaxError`. The
`betterParse` function simplifies the process by capturing
potential parsing errors and throwing more specific
exceptions, improving the overall logging and clarity of
errors encountered during JSON parsing.

Scan to Download
Example
Key Point:Improve error handling in JSON parsing
Example:When you parse a JSON string that may be
malformed, instead of failing silently, utilize a custom
error class like JSONParseError. For instance, when
receiving data from an API, if the response JSON is
invalid, using betterParse(jsonResponse) helps you
catch the specific issue. You'll see a clearer error
message rather than a generic 'SyntaxError', allowing
you to debug quicker. This can save you time when
resolving parsing issues, providing a smoother
development experience.

Scan to Download
Critical Thinking
Key Point:The introduction of a custom error type
can streamline debugging.
Critical Interpretation:While the author advocates for
the creation of a more specific error type, it is essential
to consider the increased complexity this introduces to
the codebase. Relying on custom error classes might
obscure error handling for developers unfamiliar with
the implementation, potentially defeating the purpose of
clarity that the author aims to achieve. Moreover,
standard practice often emphasizes simplicity and
minimalism in error handling, a viewpoint echoed in
works like 'JavaScript: The Good Parts' by Douglas
Crockford. Readers should weigh these competing
perspectives before adopting the author's solution.

Scan to Download
Chapter 6 Summary : 2.1. Accessing a
Given Element and Finding Its Parent
and Child Elements

2.1 Accessing a Given Element and Finding Its


Parent and Child Elements

Problem

Need to access a specific web page element and locate its


parent and child elements.

Solution

1. Assign a unique identifier to the element:


```html
<div id="demodiv"> <p> This is text. </p> </div>
```
2. Retrieve the element using `document.getElementById()`:

```javascript

Scan to Download
const demodiv = document.getElementById("demodiv");
```
3. Find its parent with the `parentNode` property:
```javascript
const parent = demodiv.parentNode;
```
4. Access its children with the `childNodes` property:
```javascript
const children = demodiv.childNodes;
```

Discussion

- The web document resembles an upside-down tree, with the


root at the top and elements branching beneath it. Each
element, except for the root, has a parent node.
- Various techniques exist for accessing document elements,
with the standardized DOM versions (Levels 2 and 3)
recommended over the older browser object model (DOM
Level 0).
- `document.getElementById()` is the common method for
Install
element Bookey
selection, App an
returning to element
Unlockobject
FullorText and
null if it
doesn’t exist. Audio
- The returned element has methods to traverse the document

Scan to Download
Chapter 7 Summary : 2.2. Traversing the
Results from querySelectorAll() with
forEach()

2.2 Traversing the Results from querySelectorAll()


with forEach()

Problem

You want to loop over the nodeList returned from a call to


querySelectorAll().

Solution

In modern browsers, you can use forEach() with a NodeList,


as follows:
```javascript
const items = document.querySelectorAll('li');
items.forEach(item => {
console.log(item.firstChild.data);
});

Scan to Download
```

Discussion

- forEach() is an Array method, but querySelectorAll()


returns a NodeList, which is not an Array.
- Modern browsers support forEach for NodeLists. However,
Internet Explorer (IE) does not.
- To support IE, a polyfill can be added:
```javascript
if (window.NodeList && !NodeList.prototype.forEach) {
NodeList.prototype.forEach = function(callback, thisArg)
{
thisArg = thisArg || window;
for (var i = 0; i < this.length; i++) {
callback.call(thisArg, this[i], i, this);
}
};
}
```
This polyfill checks for NodeList.prototype.forEach and adds
it if it doesn't exist.

2.3 Adding Up Values in an HTML Table

Scan to Download
Problem

You want to sum all numbers in a table column.

Solution

Traverse the table column with numeric strings, convert them


to numbers, and sum them:
```javascript
let sum = 0;
const cells = document.querySelectorAll('td:nth-of-type(2)');
cells.forEach(cell => {
sum += Number.parseFloat(cell.firstChild.data);
});
```

Discussion

- Use parseFloat() to handle both integers and floating-point


numbers in the HTML table.
- The sum can be used for various purposes, like database
updates or displaying messages.

Scan to Download
- You can also add a sum row to the HTML table.

Example: Converting Table Values to Numbers and


Summing the Results

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<meta http-equiv="X-UA-Compatible"
content="ie=edge">
<title>Adding Up Values in an HTML Table</title>
</head>
<body>
<h1>Adding Up Values in an HTML Table</h1>
<table>
<tbody id="table1">
<tr><td>Washington</td><td>145</td></tr>
<tr><td>Oregon</td><td>233</td></tr>
<tr><td>Missouri</td><td>833</td></tr>
</tbody>

Scan to Download
</table>
<script>
let sum = 0;
const cells = document.querySelectorAll('td + td');
cells.forEach(cell => {
sum += Number.parseFloat(cell.firstChild.data);
});
const newRow = document.createElement('tr');
const firstCell = document.createElement('td');
const firstCellText = document.createTextNode('Sum:');
firstCell.appendChild(firstCellText);
newRow.appendChild(firstCell);
const secondCell = document.createElement('td');
const secondCellText =
document.createTextNode(sum);
secondCell.appendChild(secondCellText);
newRow.appendChild(secondCell);

document.getElementById('table1').appendChild(newRow);
</script>
</body>
</html>
```

Scan to Download
Chapter 8 Summary : 2.3. Adding Up
Values in an HTML Table

Adding Up Values in an HTML Table

Problem and Solution

To sum all numbers in a specific column of an HTML table,


you can traverse the column, convert the numeric strings to
numbers, and calculate their sum.

Implementation Steps

1. Initialize a variable for the sum: `let sum = 0;`


2. Use `document.querySelectorAll()` to select all the
relevant table cells (in this case, the second cells of each
row).
3. Iterate through the selected cells and convert the text
content of each cell from a string to a number using
`Number.parseFloat()`.
4. Accumulate the total in the sum variable.

Scan to Download
Discussion

- The `parseFloat()` method is preferred over `parseInt()` for


converting strings in an HTML context, as it can process
both integers and floating-point numbers.
- After obtaining the total sum, you can use it for various
purposes, such as updating a database, displaying a message,
or appending a new row to the table with the computed sum.

Example Code

The provided example code demonstrates how to implement


the above steps, including creating a new table row at the end
of the original table to display the sum.
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<meta http-equiv="X-UA-Compatible"
content="ie=edge">

Scan to Download
<title>Adding Up Values in an HTML Table</title>
</head>
<body>
<h1>Adding Up Values in an HTML Table</h1>
<table>
<tbody id="table1">
<tr><td>Washington</td><td>145</td></tr>
<tr><td>Oregon</td><td>233</td></tr>
<tr><td>Missouri</td><td>833</td></tr>
</tbody>
</table>
<script>
let sum = 0; // Initialize sum
const cells = document.querySelectorAll('td + td'); //
Select second td elements
cells.forEach(cell => {
sum += Number.parseFloat(cell.firstChild.data); //
Sum values
});
// Create and append new row for sum
const newRow = document.createElement('tr');
const firstCell = document.createElement('td');

firstCell.appendChild(document.createTextNode('Sum:'));

Scan to Download
newRow.appendChild(firstCell);
const secondCell = document.createElement('td');

secondCell.appendChild(document.createTextNode(sum));
newRow.appendChild(secondCell);
// Add the sum row to the table

document.getElementById('table1').appendChild(newRow);
</script>
</body>
</html>
```

Scan to Download
Chapter 9 Summary : 2.4. Problem

Summarizing Table Column Sums in JavaScript

Problem

The task is to sum all numeric values present in a specific


column of an HTML table.

Solution

To achieve this, follow these steps:


1. Initialize a sum variable (e.g., `let sum = 0`).
2. Use `document.querySelectorAll()` to select all cells in the
target column (e.g., `const cells =
document.querySelectorAll('td:nth-of-type(2)')`).
3. Traverse the selected cells and convert the cell values to
numbers using `parseFloat()`. Accumulate the results in the
sum variable using `forEach()`.

Discussion

Scan to Download
- Use `parseFloat()` over `parseInt()` to handle both integers
and floating numbers effectively.
- The resulting sum can be utilized for various purposes,
including database updates, alerts, or displaying on the page.
- Optionally, a new row summarizing the total can be
appended to the table.

Example

Here’s a sample code that converts and sums the values in an


HTML table:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<meta http-equiv="X-UA-Compatible"
content="ie=edge">
<title>Adding Up Values in an HTML Table</title>
Install Bookey App to Unlock Full Text and
</head>
<body> Audio
<h1>Adding Up Values in an HTML Table</h1>

Scan to Download
Chapter 10 Summary : 2.5. Finding All
Elements That Share an Attribute

Finding All Elements That Share an Attribute

Problem

You want to find all elements in a web document that share


the same attribute.

Solution

Use the universal selector (*) in combination with the


attribute selector:
- To find all elements with a specific attribute regardless of
its value:
```javascript
const elems = document.querySelectorAll('*[class]');
```
- To find all elements with a specific attribute value:
```javascript

Scan to Download
const reds = document.querySelectorAll('*[class="red"]');
```

Discussion

- The universal selector (*) evaluates all elements, making it


ideal for verifying attributes.
- To check if an attribute exists, list the attribute name within
square brackets ([attrname]).
- Substring matching can be used if uncertain about the exact
class name:
```javascript
const reds = document.querySelectorAll('*[class*="red"]');
```
- To find elements that do NOT have a certain value, use the
:not selector:
```javascript
const notRed = document.querySelectorAll('div:not(.red)');
```

Accessing All Images in a Page

Problem

Scan to Download
You want to access all img elements in a given document.

Solution

Use the `document.getElementsByTagName()` method:


```javascript
const imgElements =
document.getElementsByTagName('img');
```

Discussion

- `getElementsByTagName()` returns a live NodeList of the


specified element type.
- The NodeList can be traversed like an array, but is not an
Array object and does not support Array methods.
- It has only the length property and the item() method:
```javascript
const img = imgElements.item(1); // second image
```
- The live collection updates automatically as the document
changes.

Scan to Download
Example Demonstration of NodeList Live Collection

```html
<!DOCTYPE html>
<html>
<head>
<title>NodeList</title>
</head>
<body>
<p></p>
<p></p>
<p></p>
<script>
const imgs = document.getElementsByTagName('img');
console.log(imgs.length);
const p = document.createElement('p');
const img = document.createElement('img');
img.src = './img/someimg.jpg';
p.appendChild(img);
const paras = document.getElementsByTagName('p');
paras[0].parentNode.appendChild(p);
console.log(imgs.length); // reflecting the new img
element added
</script>

Scan to Download
</body>
</html>
```

Scan to Download
Chapter 11 Summary : 2.6. Accessing All
Images in a Page

Accessing All Images in a Page

Problem

You want to access all `img` elements in a given document.

Solution

Use the `document.getElementsByTagName()` method,


passing in `img` as the parameter:
```javascript
const imgElements =
document.getElementsByTagName('img');
```

Discussion

The `document.getElementsByTagName()` method returns a

Scan to Download
collection of nodes (NodeList) of a given element type, such
as the `img` tag. This collection can be traversed like an
array, with the first `img` element accessible at index 0:
```javascript
const imgElements =
document.getElementsByTagName('img');
for (let i = 0; i < imgElements.length; i += 1) {
const img = imgElements[i];
...
}
```
However, a NodeList is not an Array object and does not
support methods like `push()` and `reverse()`. Its only
property is `length`, and its only method is `item()`, which
returns the element at a specified index:
```javascript
const img = imgElements.item(1); // second image
```
NodeList is a live collection, meaning it updates to reflect
changes made to the document after retrieval.

Example

Example 2-2 demonstrates the functionality of

Scan to Download
getElementsByTagName and the live collection property of
NodeList. Three images are accessed, and their count is
output. A new paragraph and image are created and appended
to the parent element, which results in the NodeList updating
to reflect the new count:
```html
<!DOCTYPE html>
<html>
<head>
<title>NodeList</title>
</head>
<body>
<p></p>
<p></p>
<p></p>
<script>
const imgs = document.getElementsByTagName('img');
console.log(imgs.length);
const p = document.createElement('p');
const img = document.createElement('img');
img.src = './img/someimg.jpg';
p.appendChild(img);
const paras = document.getElementsByTagName('p');
paras[0].parentNode.appendChild(p);

Scan to Download
console.log(imgs.length);
</script>
</body>
</html>
```

Scan to Download
Chapter 12 Summary : 2.7. Discovering
All Images in Articles Using the Selectors
API

Discovering All Images in Articles Using the


Selectors API

Problem

You want to get a list of all img elements that are


descendants of article elements without traversing the entire
element collection.

Solution

Use the Selectors API with CSS-style selector strings:


```javascript
const imgs = document.querySelectorAll('article img');
```

Discussion

Scan to Download
- Two methods in the selectors API: `querySelectorAll()`
(returns all matching elements) and `querySelector()` (returns
the first matching element).
- The selector syntax is similar to CSS but returns elements
to the application instead of styling them.
- Different selectors can target various descendent
relationships, such as:
- All img elements: `querySelectorAll('img')`
- Direct children of article: `querySelectorAll('article >
img')`
- Followed by a paragraph: `querySelectorAll('img + p')`
- Images with or without empty alt attributes:
`querySelectorAll('img[alt=""]')`,
`querySelectorAll('img:not([alt=""])')`
- Note that collections from `querySelectorAll()` are not
“live”, meaning updates to the document won’t affect the
collection post-retrieval.

Caution

TheInstall Bookey
Selectors App tobut
API is powerful Unlock
should Full Text more
not replace and
Audio
efficient methods like `getElementById()` for specific
elements.

Scan to Download
Chapter 13 Summary : 2.8. Setting an
Element’s Style Attribute

Setting an Element’s Style Attribute

Problem

You want to add or replace a style setting on a specific web


page element.

Solution

To change a single CSS property, modify its value through


the element’s style property:
`elem.style.backgroundColor = 'red';`
To modify one or more CSS properties for a single element,
use `setAttribute()` to create an entire CSS style rule:
`elem.setAttribute('style', 'background-color: red; color:
white; border: 1px solid black');`
Alternatively, predefine the style rule, assign it a class name,
and set the class property for the element:

Scan to Download
```css
.stripe {
background-color: red;
color: white;
border: 1px solid black;
}
```
`elem.setAttribute('class', 'stripe');`

Discussion

CSS properties can be modified in JavaScript using three


main approaches:
1.
Direct property access
: The simplest method is to modify the element’s style
property directly, e.g.,
`elem.style.width = '500px';`

2.
Using `setAttribute()`
: This allows you to set multiple CSS properties at once.
However, this method requires all properties to be specified
simultaneously as it will erase previously set values.

Scan to Download
3.
Modifying the class attribute
: Change the class of the element using:
`elem.setAttribute('class', 'classname');`

Advanced Techniques

For more complex scenarios, create an attribute and attach it


to the element using `createAttribute()`:
```javascript
const styleAttr = document.createAttribute('style');
styleAttr.nodeValue = 'background-color: red';
someElement.setAttribute(styleAttr);
```
Use `createAttribute()` only if you need to create an entity
reference that `setAttribute()` cannot handle.

Accessing Existing Style Settings

To access existing attribute values, use `getAttribute()`:


`const className =
document.getElementById('elem1').getAttribute('class');`
Accessing style settings is more complicated as it relies on
the computed style of the element. Use

Scan to Download
`window.getComputedStyle()` to obtain the current applied
styles:
`const style = window.getComputedStyle(elem);`

Inserting a New Paragraph

Problem

You want to insert a new paragraph just before the third


paragraph within a div element.

Solution

Access the third paragraph using


`getElementsByTagName()`, then use `createElement()` and
`insertBefore()` to add the new paragraph:
```javascript
const div = document.getElementById('target');
const paras = div.getElementsByTagName('p');
const newPara = document.createElement('p');
const text = document.createTextNode('New paragraph
content');
newPara.appendChild(text);

Scan to Download
if (paras[2]) {
div.insertBefore(newPara, paras[2]);
} else {
div.appendChild(newPara);
}
```

Discussion

The `document.createElement()` method creates HTML


elements that can be inserted or appended into the page. To
insert a new paragraph before the existing third paragraph,
retrieve a collection of paragraphs, check for the existence of
a third paragraph, and use `insertBefore()`. If the third
paragraph does not exist, append the new paragraph to the
end of the div.

Scan to Download
Chapter 14 Summary : 2.9. Inserting a
New Paragraph

Inserting a New Paragraph

Problem

You want to insert a new paragraph just before the third


paragraph within a div element.

Solution

To solve this problem, use methods like


`getElementsByTagName()` to access all paragraphs within
the div. Then, apply `createElement()` and `insertBefore()`
methods to position the new paragraph correctly. Below is
the implementation:
```javascript
// get the target div
const div = document.getElementById('target');
// retrieve a collection of paragraphs

Scan to Download
const paras = div.getElementsByTagName('p');
// create the element and append text to it
const newPara = document.createElement('p');
const text = document.createTextNode('New paragraph
content');
newPara.appendChild(text);
// if a third para exists, insert the new element before
// otherwise, append the paragraph to the end of the div
if (paras[2]) {
div.insertBefore(newPara, paras[2]);
} else {
div.appendChild(newPara);
}
```

Discussion

The `document.createElement()` method generates a new


HTML element which can then be appended or inserted into
the page. The approach outlined allows you to insert a new
paragraph before an existing third paragraph, if it exists. If
the third paragraph is not present, the new element will be
appended to the end of the div using `appendChild()`.

Scan to Download
About the Author

-
John Paxton
: Over 20 years in programming and web technologies,
focusing on JavaScript and Java. Enjoys beer, movies, and
traveling.
-
Adam D. Scott
: Engineering manager and web developer at the Consumer
Financial Protection Bureau, author of several technical
books.
-
Shelley Powers
: Experienced in web technologies, author of numerous
publications covering aspects of JavaScript and web
development. Hobbyist photographer.

Colophon

The cover of "JavaScript Cookbook, Second Edition"


features the little egret, a notable bird found in various
regions around the world, known for its fishing techniques
and breeding patterns.

Scan to Download
Best Quotes from JavaScript Cookbook
by Shelley Powers with Page Numbers
View on Bookey Website and Generate Beautiful Quote Images

Chapter 1 | Quotes From Pages 4-21


1.Errors often do not show up in the HTML of a
page, as they are re-routed to the console.
2.Rather than to try to bring JavaScript back into a correct
state (which may, in fact, be impossible!).
3.TypeError covers issues where the expected value was of
the wrong type.
4.You can create your own Error types?
5.If some other error is raised (it could happen), we will pass
that error along as-is, with no modification or re-packaging.
Chapter 2 | Quotes From Pages 22-37
1.JavaScript has seven subtypes of Error. We can
check for a subtype of error to determine the kind
of error raised by a problem in our code.
2.The problem is that JavaScript permits only one catch
block, offering neither opportunity nor syntax to capture

Scan to Download
errors by their type.
3.Handling errors, even by their subtype, is fraught with
difficulties in JavaScript.
4.Errors often do not show up in the HTML of a page, as
they are re-routed to the console.
5.If you are going to use Errors to express incorrect states for
your application, the TypeError and RangeError hold some
promise.
Chapter 3 | Quotes From Pages 38-49
1.If you are going to use Errors to express incorrect
states for your application, the TypeError and
RangeError hold some promise.
2.Include the given value and information about the expected
value.
3.Invalid user data should be an expected state of your code,
and should be handled in a user-friendly manner.
4.When subclassing Error, we should keep in mind two
possibly competing concerns: staying within the bounds of
a typical JavaScript error, and expressing enough

Scan to Download
information for our customized error.
5.We would like to log a specific error type when
JSON.parse encounters an error.

Scan to Download
Chapter 4 | Quotes From Pages 50-59
1.When subclassing Error, we should keep in mind
two possibly competing concerns: staying within
the bounds of a typical JavaScript error, and
expressing enough information for our customized
error.
2.Do not over-extend JavaScript’s Error type with extra
methods and properties.
3.Using ECMAScript 2015’s rest parameter feature to
vacuum up any remaining arguments.
4.Recognizing the need for a specific error type can improve
logging and error handling practices when dealing with
JSON parsing.
5.If some other error is raised (it could happen), we will pass
that error along as-is, with no modification or re-packaging.
Chapter 5 | Quotes From Pages 60-65
1.JavaScript Object Notation has become a popular,
portable data format thanks in part to the
popularity of JavaScript.

Scan to Download
2.A SyntaxError is raised when JavaScript tries to interpret
syntactically invalid code.
3.We would like to log a specific error type when
JSON.parse encounters an error.
4.If a SyntaxError is raised, we will re-package it as a
JSONParseError.
Chapter 6 | Quotes From Pages 69-94
1.A web document is organized like an upside-down
tree, with the topmost element at the root and all
other elements branching out beneath.
2.But you’ll always want to use the most restrictive method
possible, and you can’t get more restrictive than
document.getElementById().
3.The best way to see how messy the DOM can be is to use a
debugger such as the Firefox or Chrome developer tools...
4.the parseInt() and parseFloat() methods convert strings to
numbers, but parseFloat() is more adaptable when it comes
to handling numbers in an HTML table.

Scan to Download
Chapter 7 | Quotes From Pages 95-114
1.forEach() is an Array method, but the results of
querySelectorAll() is a NodeList which is a
different type of object than an Array.
2.Thankfully, modern browsers have built in support for
forEach, allowing us to iterate over a NodeList like an
array.
3.In the polyfill, we check for the existence of
Nodelist.prototype.forEach.
4.The parseInt() and parseFloat() methods convert strings to
numbers, but parseFloat() is more adaptable when it comes
to handling numbers in an HTML table.
5.Once you have the sum, you can use it in a database
update, pop up a message box, or print it to the page.
6.This selector finds all table cells that are preceded by
another table cell.
Chapter 8 | Quotes From Pages 115-136
1.parseFloat() is more adaptable when it comes to
handling numbers in an HTML table.

Scan to Download
2.As you traverse the HTML table and convert the table
entries to numbers, sum the results.
3.You can also add a sum row to the HTML table.
4.document.querySelectorAll() uses a different variation on
the CSS selector, td + td, to access the data this time.
Chapter 9 | Quotes From Pages 137-159
1.The parseInt() and parseFloat() methods convert
strings to numbers, but parseFloat() is more
adaptable when it comes to handling numbers in
an HTML table.
2.Once you have the sum, you can use it in a database
update, pop up a message box, or print it to the page.
3.You can also add a sum row to the HTML table.

Scan to Download
Chapter 10 | Quotes From Pages 160-176
1.The universal selector (*) evaluates all elements, so
it’s the one you want to use when you need to
verify something about each element.
2.To test whether an attribute exists, all you need to do is list
the attribute name within square brackets ([attrname]).
3.The NodeList collection can be traversed like an array, but
it isn’t an Array object—you can’t use Array object
methods, such as push() and reverse(), with a NodeList.
4.NodeList is an intriguing object because it’s a live
collection, which means changes made to the document
after the NodeList is retrieved are reflected in the
collection.
Chapter 11 | Quotes From Pages 177-193
1.The NodeList collection can be traversed like an
array, but it isn’t an Array object—you can’t use
Array object methods, such as push() and
reverse(), with a NodeList.
2.NodeList is an intriguing object because it’s a live

Scan to Download
collection, which means changes made to the document
after the NodeList is retrieved are reflected in the
collection.
Chapter 12 | Quotes From Pages 194-208
1.const imgs = document.querySelectorAll('article
img');
2.The negation pseudoselector (:not) is used to find all img
elements with alt attributes that are not empty.
3.Though the Selectors API is a wonderful creation, it
shouldn’t be used for every document query.
4.element.style.backgroundColor = 'red';
5.The document.createElement() method creates any HTML
element, which then can be inserted or appended into the
page.

Scan to Download
Chapter 13 | Quotes From Pages 209-219
1.An element’s CSS properties can be modified in
JavaScript using one of three approaches.
2.If the CSS property contains a hyphen, such as font-family
or background-color, use the CamelCase notation for the
property.
3.You can add any number of attributes to an element using
either createAttribute() and setAttribute(), or setAttribute()
directly.
4.Getting access to a style setting, though, is much trickier,
because a specific element’s style settings at any one time
is a composite of all settings merged into a whole.
Chapter 14 | Quotes From Pages 220-227
1.The document.createElement() method creates any
HTML element, which then can be inserted or
appended into the page.
2.Because we’re interested in inserting the new paragraph
before the existing third paragraph, we need to retrieve a
collection of the div element’s paragraphs, check to make

Scan to Download
sure a third paragraph exists, and then use insertBefore() to
insert the new paragraph before the existing one.
3.If the third paragraph doesn’t exist, we can append the
element to the end of the div element using appendChild().

Scan to Download
JavaScript Cookbook Questions
View on Bookey Website

Chapter 1 | 1.1. Using Errors| Q&A


1.Question
What are the key properties of a JavaScript Error
object?
Answer:A JavaScript Error object typically includes
three key properties: a constructor, a name, and a
message. Additionally, Error objects have a
toString() method that usually returns the message
property.

2.Question
How do you create and catch a standard error in
JavaScript?
Answer:To create and catch a standard error, you can
instantiate an Error object with a descriptive string, throw it
using the 'throw' keyword, and wrap the code in a try-catch
block to handle it. For example:

Scan to Download
```javascript
function willThrowError() {
if (/* something goes wrong */) {
throw new Error(`Problem in ${method}, ${reason}`);
}
}
try {
willThrowError();
} catch (error) {
console.error('There was an error: ', error);
}
```

3.Question
What is the importance of checking error subtypes in
JavaScript?
Answer:Checking error subtypes is important because it can
provide more specific information about the nature of the
error, potentially enabling recovery or at least better handling
of the error situation. For instance, responding differently to

Scan to Download
a TypeError versus a RangeError can lead to more
informative debugging and user responses.

4.Question
How can we create custom error types in JavaScript?
Answer:To create custom error types, you can subclass the
built-in Error class using the ECMAScript 2015 class syntax.
You define a new class and call the super() method to ensure
it inherits properties from the Error class. For example:

```javascript
class CustomError extends Error {
constructor(customProp='customValue', ...params) {
super(...params);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CustomError);
}
this.name = 'CustomError';
this.customProp = customProp;
}

Scan to Download
}
```

5.Question
What should you do when handling JSON parsing
errors?
Answer:When handling JSON parsing errors, it is
recommended to create a custom error subclass of
SyntaxError to provide clearer context for JSON parsing
issues. This makes it easier to identify and respond to such
errors. For example, you can implement a better error
handling mechanism as follows:

```javascript
class JSONParseError extends SyntaxError {
constructor(...params) {
super(...params);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, JSONParseError);
}

Scan to Download
this.name = 'JSONParseError';
}
}

function betterParse(jsonString) {
try {
return JSON.parse(jsonString);
} catch (err) {
if (err instanceof SyntaxError) {
throw new JSONParseError(err);
} else {
throw err;
}
}
}
```

6.Question
Why is it suggested not to validate forms with errors?
Answer:It is suggested not to validate forms with errors

Scan to Download
because error messages often do not provide clear or
user-friendly feedback to the user. Invalid user data should be
handled in a way that does not disrupt the user experience,
utilizing native APIs or custom event-driven validation
methods instead.
Chapter 2 | 1.2. Capturing Errors by their subtypes|
Q&A
1.Question
What are the seven subtypes of Error in JavaScript and
why is understanding them important?
Answer:The seven subtypes of Error in JavaScript
are:
1. EvalError - related to the eval() function.
2. InternalError - non-standard internal engine
errors.
3. RangeError - a value is outside its valid range.
4. ReferenceError - dereferencing an invalid
reference.
5. SyntaxError - issues with the syntax of evaluated
code, including JSON.

Scan to Download
6. TypeError - a variable or parameter is of an
unexpected type.
7. URIError - issues with encodeURI() and
decodeURI().
Understanding these subtypes is crucial because
they help pinpoint specific problems in code and
may offer paths for recovery or provide key
information about issues.

2.Question
How can you catch errors by their subtype in a catch
block?
Answer:To catch errors by their subtype in a catch block, use
the 'instanceof' operator to check the error type. For example:

```javascript
try {
// Some code that raises an error
} catch (err) {
if (err instanceof RangeError) {

Scan to Download
// Handle the RangeError specifically
} else if (err instanceof TypeError) {
// Handle the TypeError specifically
} else {
// Rethrow the error for further handling
throw err;
}
}
```
This checks the specific error type and allows for tailored
error handling.

3.Question
What are TypeError and RangeError, and how can they
be used effectively in code?
Answer:TypeError indicates that a variable or parameter is of
an unexpected type, while RangeError indicates that a value
is outside of its accepted range. They can be used effectively
in code by throwing them when invalid input is detected:
- For TypeError:

Scan to Download
```javascript
function calculateValue(x) {
if (typeof x !== 'number') {
throw new TypeError(`Value [${x}] is not a number.`);
}
// Perform calculation
}
```
- For RangeError:
```javascript
function setAge(age) {
const upper = 125;
const lower = 18;
if (age > upper || age < lower) {
throw new RangeError(`Age [${age}] is out of acceptable
range [${lower} to ${upper}].`);
}
}
```

Scan to Download
Making sure the error messages are informative helps users
understand the issues.

4.Question
How can you create custom error subtypes in JavaScript?
Answer:You can create custom error subtypes by subclassing
the Error class using ECMAScript 2015 class syntax. Here's
an example of creating a CustomError class:
```javascript
class CustomError extends Error {
constructor(customProp='customValue', ...params) {
super(...params);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CustomError);
}
this.name = 'CustomError';
this.customProp = customProp;
}
}
```

Scan to Download
This allows you to maintain standard error functionality
while adding your properties.

5.Question
Why is it important to handle JSON parsing errors
specifically?
Answer:Handling JSON parsing errors specifically is
important because the errors that arise during this process
often result in SyntaxErrors, which are too vague for
identifying issues with JSON data. To improve error
handling, you can create a custom error class,
JSONParseError, and repackage any SyntaxErrors raised
during JSON parsing to provide clearer messages and better
handling in your application. This enables both users and
developers to identify issues more effectively.

6.Question
What should you avoid when using errors in JavaScript
for user input validation?
Answer:You should avoid using errors for validating user
input, as errors are typically not user-friendly and may not

Scan to Download
display helpful information on the user interface. Instead,
utilize form validation APIs or event-based validation hooks,
as these methods provide clearer, more informative feedback
to users without disrupting the user experience.
Chapter 3 | 1.3. Throwing useful errors| Q&A
1.Question
Why should we use specific Error subtypes like
TypeError and RangeError?
Answer:Using specific Error subtypes helps to
convey more precise information about the nature of
the error. For example, TypeError indicates that a
value is the wrong type, while RangeError signifies
that a value is outside an acceptable range. This
specificity allows developers to understand and fix
errors more efficiently, ensuring better debugging
and maintenance of the code.

2.Question
What is a potential problem with using the general Error
type?

Scan to Download
Answer:The general Error type can be too broad and vague,
making it difficult to diagnose specific issues. By subclassing
Error into more specific types, developers can provide clearer
context and details about the error encountered, thus
improving error handling and readability in the code.

3.Question
How do you create a custom Error subtype in
JavaScript?
Answer:To create a custom Error subtype, you can subclass
the built-in Error class using the ECMAScript 2015 class
syntax. You need to call the superclass constructor with
appropriate arguments, optionally define custom properties,
and set the name property to ensure it reflects your custom
class. For example:

```javascript
class CustomError extends Error {
constructor(customProp='customValue', ...params) {
super(...params);

Scan to Download
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CustomError);
}
this.name = 'CustomError';
this.customProp = customProp;
}
}
```

4.Question
When should you prefer to use forms of validation rather
than throwing errors?
Answer:You should prefer to use forms of validation when
dealing with user input, such as validating form fields.
Unlike errors, validation mechanisms provide user-friendly
feedback and guidance to help correct input issues before
they cause exceptions in the code. Using native APIs or
user-friendly error messages ensures that users can interact
with the application effectively without encountering harsh
error states.

Scan to Download
5.Question
Why is it important to provide informative error
messages?
Answer:Informative error messages are crucial as they guide
developers in understanding what went wrong. Including
details about the received value and the expected type or
range helps in diagnosing issues quickly. Without useful
error messages when an exception occurs, diagnosing and
fixing bugs becomes more time-consuming and difficult.

6.Question
What should you do if JSON parsing raises a
SyntaxError?
Answer:If a SyntaxError occurs during JSON parsing,
re-throw it as a specific custom error type, such as
JSONParseError, to differentiate it from other SyntaxErrors.
This allows for more precise error handling and logging that
specifically pertains to JSON parsing issues. Define a custom
error class like so:

Scan to Download
```javascript
class JSONParseError extends SyntaxError {
constructor(...params) {
super(...params);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, JSONParseError);
}
this.name = 'JSONParseError';
}
}
```.

7.Question
How should you handle invalid user data in your
application?
Answer:Invalid user data should be expected and should not
cause your application to throw uncaught exceptions. Instead,
handle such data gracefully using validation frameworks,
user feedback mechanisms, or preemptive checks to ensure
that user inputs are correct before they reach processing

Scan to Download
functions.

8.Question
What’s the benefit of subclassing the Error class?
Answer:Subclassing the Error class allows developers to
create more granular error types that can encapsulate
additional information about specific types of errors. This
provides better context for debugging and user reporting,
ultimately leading to improved software quality and
maintenance.

Scan to Download
Chapter 4 | 1.4. Throwing custom errors| Q&A
1.Question
Why is it important to create custom Error types in
JavaScript?
Answer:Creating custom Error types allows you to
provide more specific error handling, making it
easier to identify, debug, and manage errors related
to your code. For example, by subclassing the Error
type, you can create an error that conveys specific
problems like a failed JSON parsing instead of a
generic message, which enhances maintainability
and readability.

2.Question
What are key considerations when subclassing the Error
object in JavaScript?
Answer:When subclassing the Error object, it is vital to
maintain conformity with the standard JavaScript error
structure while adding additional information. This includes
properly using the error constructor parameters, setting the

Scan to Download
correct stack trace, and ensuring the name of the error reflects
its subclass. This strategy enables future developers to
intuitively understand and handle your custom error types.

3.Question
How does using the ECMAScript 2015 class syntax
benefit custom error creation?
Answer:Using the ECMAScript 2015 class syntax
streamlines the process of creating custom Error types by
leveraging class inheritance features, which promote cleaner
and more organized code. It allows developers to extend
built-in objects without the complexity of manual prototype
manipulation, making the code more intuitive and easier to
follow.

4.Question
What is a potential issue with the default SyntaxError
when parsing JSON, and how can it be mitigated?
Answer:The default SyntaxError raised during JSON parsing
can be too broad and lack detail. This can be mitigated by
creating a custom JSONParseError class that extends

Scan to Download
SyntaxError, allowing developers to catch and handle
JSON-specific errors distinctly. Utilizing a wrapper function
like betterParse can simplify error handling by consistently
converting SyntaxErrors into JSONParseErrors.

5.Question
Describe the purpose and advantage of the betterParse
function.
Answer:The betterParse function aims to encapsulate the
JSON parsing logic along with robust error handling. By
catching SyntaxErrors and transforming them into
JSONParseErrors, it simplifies error management for
developers, allowing clear differentiation between JSON
issues and other errors. This encapsulation enhances code
clarity, reusability, and reduces boilerplate error handling
code throughout applications.

6.Question
How does setting the name property in custom error
classes benefit error handling?
Answer:Setting the name property in custom error classes

Scan to Download
allows developers to identify specific error types directly in
logs or catch blocks. This clear distinction helps in
debugging and tracking issues more effectively as they can
immediately see which error occurred without needing to
inspect stack traces or messages.

7.Question
Discuss the significance of stack trace management in
custom error classes.
Answer:Proper management of stack traces in custom error
classes ensures that when an error is thrown, it retains vital
context about where the error occurred in the code. By using
Error.captureStackTrace, developers can capture the stack
trace accurately, making debugging significantly easier by
providing clear insights into the execution flow leading to the
error.

8.Question
Why is it recommended to keep custom properties
separate from standard error properties?
Answer:Keeping custom properties separate from standard

Scan to Download
error properties ensures clarity and avoids confusion. It
allows developers to set additional information relevant to
their specific error without interfering with standard expected
parameters, thereby maintaining consistent behavior with
JavaScript's built-in error handling.

9.Question
What problem arises from over-extending the built-in
Error type and how can this be avoided?
Answer:Over-extending the built-in Error type can lead to
maintenance challenges and unexpected behaviors, as other
developers may not assume or understand the additional
methods and properties. To avoid this, it's best to stick to a
limited and well-defined extension of the Error class that
maintains compatibility with standard error handling
practices.

10.Question
In what way does creating a JSONParseError improve
logging and error handling?
Answer:Creating a JSONParseError refines the error

Scan to Download
handling process by providing a specific identifier for JSON
parsing issues. This improvement allows for better logging
practices, making it easier to filter and analyze errors related
only to JSON parsing, rather than sorting through all types of
SyntaxErrors.
Chapter 5 | 1.5. Handling JSON parsing errors|
Q&A
1.Question
What is the main issue when parsing JSON strings in
JavaScript?
Answer:The main issue when parsing JSON strings
in JavaScript is that if the JSON is malformed or
not formatted correctly, it results in a generic
SyntaxError, which lacks detail and can make
debugging difficult.

2.Question
How can we improve error handling during JSON
parsing?
Answer:We can improve error handling by creating a custom
error class, `JSONParseError`, which extends the standard

Scan to Download
SyntaxError. This subclass provides a more specific type of
error for JSON parsing issues, allowing developers to handle
JSON-related errors more effectively.

3.Question
What is the purpose of the `betterParse` function?
Answer:The `betterParse` function wraps the standard
`JSON.parse` method in a try-catch block. It catches
SyntaxErrors and rethrows them as `JSONParseError`, thus
providing more context about the error when parsing fails.

4.Question
Why is it important to have a specific error type for
JSON parsing?
Answer:Having a specific error type for JSON parsing is
important because it enhances error logging and allows
developers to implement more precise error handling
mechanisms rather than dealing with generic SyntaxErrors
that do not convey specific information.

5.Question
What simple steps can be taken to enhance the usability
and security of JSON parsing in JavaScript?

Scan to Download
Answer:To enhance usability and security of JSON parsing,
developers can implement functions like `betterParse` that
manage errors effectively and improve feedback. They
should also perform validation on JSON inputs to reduce the
chances of encountering malformed data.

6.Question
How can the `JSONParseError` class benefit consumers
of the API dealing with JSON?
Answer:The `JSONParseError` class benefits consumers of
the API by allowing them to specifically catch JSON-related
parsing errors and handle them in a tailored way, improving
the overall robustness and clarity of error management in
their applications.

7.Question
In what way does `JSON.stringify` differ from
`JSON.parse` in terms of error handling?
Answer:`JSON.stringify` generally does not raise errors,
unless there are issues with the JavaScript object being
processed. In contrast, `JSON.parse` can raise various errors

Scan to Download
due to malformed JSON strings, making its error handling
more critical and complex.

8.Question
How does creating a custom error type like
`JSONParseError` clarify the debugging process?
Answer:By using a custom error type like `JSONParseError`,
developers can quickly identify issues specifically related to
JSON parsing, leading to more efficient debugging. This
distinction helps in isolating JSON errors from other
potential code issues.
Chapter 6 | 2.1. Accessing a Given Element and
Finding Its Parent and Child Elements| Q&A
1.Question
How do you uniquely identify an element in a webpage
using JavaScript?
Answer:You can uniquely identify an element by
assigning it a unique identifier using the 'id'
attribute. For example: <div id="demodiv">. Once
an element has a unique 'id', you can reference it in
JavaScript using

Scan to Download
document.getElementById('demodiv');.

2.Question
What is the purpose of the parentNode property in the
DOM?
Answer:The parentNode property is used to access the parent
element of a given node in the DOM. For example, if you
have an element 'demodiv', you can find its parent by writing
const parent = demodiv.parentNode;.

3.Question
How can you retrieve child elements from a DOM node?
Answer:You can retrieve child elements from a DOM node
by using the childNodes property. For instance, with
demodiv.childNodes, you can access all child nodes of the
'demodiv' element, which may include text nodes and
element nodes.

4.Question
Why is it important to understand the structure of the
DOM as being tree-like?
Answer:Understanding the DOM as an upside-down tree
helps you visualize how elements are nested within one

Scan to Download
another. This hierarchical view clarifies how to navigate
through elements, finding parents, children, and siblings
effectively.

5.Question
What should developers consider when using different
methods to access webpage elements?
Answer:Developers should use the most restrictive method
possible for accessing elements. For example,
document.getElementById() is often preferred because it
directly references a single element by its unique id, making
it efficient and fast.

6.Question
What is the significance of the nodeName property in the
DOM?
Answer:The nodeName property provides the type of the
current node, such as 'DIV', 'P', or '#text' for text nodes. This
information is useful for understanding what kind of
elements you are working with during DOM manipulation.

7.Question
What method can you use to iterate over a NodeList

Scan to Download
returned by querySelectorAll in modern browsers?
Answer:You can use the forEach() method to iterate over a
NodeList. This allows you to easily apply a function to each
item in the list, similar to how you would with an array.

8.Question
How can you sum numeric values in a column of an
HTML table?
Answer:To sum numeric values in a table column, you can
select all relevant table cells using querySelectorAll() and
then convert the values to numbers (using parseFloat) as you
iterate over them to accumulate the sum. After calculating
the sum, you can display it in the table or use it otherwise.

9.Question
What is a polyfill and when would you need to use one
regarding the NodeList forEach method?
Answer:A polyfill is code that provides functionality that is
usually built into modern browsers, allowing older browsers
to support it. You would need to use a polyfill for the
NodeList forEach method if you want to support older

Scan to Download
versions of Internet Explorer that do not support forEach
natively.

10.Question
How can you visually inspect the structure of a webpage's
DOM?
Answer:You can visually inspect the structure of a webpage's
DOM by using developer tools available in browsers like
Firefox and Chrome. These tools allow you to see the
element tree of a webpage, making it easier to understand the
relationships between various DOM nodes.

Scan to Download
Chapter 7 | 2.2. Traversing the Results from
querySelectorAll() with forEach()| Q&A
1.Question
How can I loop over a NodeList returned by
querySelectorAll in modern browsers?
Answer:You can use the forEach() method directly
on the NodeList, for example:

```javascript
const items = document.querySelectorAll('li');
items.forEach(item => {
console.log(item.firstChild.data);
});
``` This will log the data of the first child of each list
item.

2.Question
What if I want to support Internet Explorer when using
forEach on NodeList?
Answer:Internet Explorer does not support forEach on
NodeLists. To ensure compatibility, you can write a polyfill

Scan to Download
that adds a forEach method to the NodeList prototype:

```javascript
if (window.NodeList && !NodeList.prototype.forEach) {
NodeList.prototype.forEach = function(callback, thisArg)
{
thisArg = thisArg || window;
for (var i = 0; i < this.length; i++) {
callback.call(thisArg, this[i], i, this);
}
};
}
``` This way, you can use the forEach syntax freely across
your codebase.

3.Question
How can I sum all numbers in a specific column of an
HTML table?
Answer:First, you can use querySelectorAll to select all cells
in the specified column, convert the string values to numbers

Scan to Download
using parseFloat, and then sum them:

```javascript
let sum = 0;
const cells = document.querySelectorAll('td:nth-of-type(2)');
cells.forEach(cell => {
sum += Number.parseFloat(cell.firstChild.data);
});
``` This code iterates over the selected cells and adds their
numeric values to the sum.

4.Question
Why is parseFloat preferred over parseInt when dealing
with numbers in an HTML table?
Answer:parseFloat is more flexible than parseInt because it
can handle both integers and floating-point numbers. If you
are not sure whether the numbers in your table will be whole
numbers or decimals, using parseFloat prevents potential
errors from using parseInt.

5.Question

Scan to Download
How do I add a new row containing the sum to the end of
an HTML table?
Answer:You can create a new row and append it to the table
as follows:

```javascript
const newRow = document.createElement('tr');
const firstCell = document.createElement('td');
firstCell.appendChild(document.createTextNode('Sum:'));
newRow.appendChild(firstCell);

const secondCell = document.createElement('td');


secondCell.appendChild(document.createTextNode(sum));
newRow.appendChild(secondCell);

document.getElementById('table1').appendChild(newRow);
``` This creates a new table row with the sum and adds it to
the specified table.

6.Question

Scan to Download
What is the purpose of using `td + td` in the
querySelectorAll for table cells?
Answer:The selector `td + td` is used to select all second
table cells that are immediately preceded by another table
cell. This allows you to specifically target the column
containing the numeric values you want to sum, ensuring the
correct data is processed.
Chapter 8 | 2.3. Adding Up Values in an HTML
Table| Q&A
1.Question
What is the primary goal when summing values in an
HTML table?
Answer:The primary goal is to traverse a specific
column of the table containing numeric string
values, convert these strings into numbers, and
compute the total sum of these numbers.

2.Question
Why is parseFloat() preferred over parseInt() for this
task?
Answer:parseFloat() is preferred because it can handle both

Scan to Download
floating-point numbers and integers, making it more
adaptable for various numeric formats that might appear in
an HTML table.

3.Question
How do you access all cells in a specific column of an
HTML table?
Answer:You can access all cells in a specific column by
using the CSS selector 'td + td' with the
document.querySelectorAll() method, which selects all
second table cells that follow another table cell.

4.Question
What is an example of what you can do with the
computed sum after calculating it?
Answer:After computing the sum, you can display it in a
message box, update a database, or insert a new row in the
HTML table to show the total sum.

5.Question
How do you dynamically add a new row to the table
displaying the sum?
Answer:To add a new row, you would create a new <tr>

Scan to Download
element, append a <td> for the label 'Sum:', and another <td>
for the computed sum, and then append this new row to the
existing table body.

6.Question
Can you explain the significance of the 'td + td' selector in
your JavaScript code?
Answer:The 'td + td' selector is significant because it selects
all second table cells ('td') in each row, allowing you to
specifically target the column that you want to sum without
affecting other columns.

7.Question
In a real-world scenario, why might you need to sum
values in an HTML table?
Answer:In a real-world scenario, summing values might be
necessary in applications like shopping carts where you want
to calculate total prices, in reports to summarize data, or in
analytical dashboards to provide insights from collected data.
Chapter 9 | 2.4. Problem| Q&A
1.Question
What is the primary goal of the code presented in the

Scan to Download
excerpt from Chapter 9?
Answer:The primary goal of the code is to calculate
the sum of numeric values found in the second
column of an HTML table and display this sum as a
new row at the end of the table.

2.Question
Why is parseFloat() preferred over parseInt() when
handling numeric values in this case?
Answer:parseFloat() is preferred because it is capable of
handling both integers and floating-point numbers, making it
more adaptable for values that could be presented in decimal
form.

3.Question
What is the significance of using 'td + td' in the
querySelectorAll statement?
Answer:Using 'td + td' in the querySelectorAll allows the
code to select every second table cell by targeting cells that
directly follow another table cell, ensuring that only the
correct numeric values are accessed for summation.

Scan to Download
4.Question
Can you explain how the sum is integrated back into the
HTML table after calculation?
Answer:After calculating the sum, a new table row is created
and filled with two cells: the first cell contains the label
'Sum:', and the second cell contains the computed sum. This
new row is then appended to the existing table to visually
present the total.

5.Question
How could the calculated sum be used in practical
applications beyond just displaying it in the table?
Answer:The calculated sum could be utilized for various
applications such as updating a database with new totals,
generating reports, or sending alerts (like a message box)
based on the summed values, thereby enhancing user
interactivity and data tracking.

6.Question
What would happen if some values in the second column
were not numeric? How does the code handle such
scenarios?

Scan to Download
Answer:If some values are not numeric, parseFloat() will
convert them to NaN (not a number), which would not affect
the summation since NaN results in a non-numeric addition.
It is good practice to ensure all values are numeric
beforehand or to handle NaN cases appropriately to avoid
misleading results.

7.Question
What additional features could be added to improve the
usability of this table and its summation functionality?
Answer:Additional features could include dynamic updates
that recalculate the sum as values change, validation to
ensure only numeric entries are allowed, filtering
capabilities, or integrating with a charting library for visual
data representation.

Scan to Download
Chapter 10 | 2.5. Finding All Elements That Share
an Attribute| Q&A
1.Question
How can you find all elements in a web document that
share a specific attribute?
Answer:You can use the universal selector (*) in
combination with the attribute selector to find all
elements that have an attribute regardless of its
value. For example, the code 'const elems =
document.querySelectorAll('*[class]');' finds all
elements with a class attribute. If you want to find
elements that share a specific value for that
attribute, you would use 'const reds =
document.querySelectorAll('*[class="red"]');'
which only selects elements with a class attribute
specifically set to 'red'.

2.Question
What is the purpose of using the :not negation operator in
a query?
Answer:The :not negation operator allows you to exclude

Scan to Download
specific elements from your selections. For example, 'const
notRed = document.querySelectorAll('div:not(.red)');' will
select all div elements that do not have the class 'red'. This is
particularly useful when you want to perform actions or
selections without including certain elements.

3.Question
What does the getElementsByTagName() method do?
Answer:The getElementsByTagName() method retrieves all
elements of a specified type from the document and returns
them as a live NodeList. For example, 'const imgElements =
document.getElementsByTagName('img');' will return all
<img> elements in the document, and this list will
automatically update if new <img> elements are added to the
document afterward.

4.Question
Is a NodeList created by getElementsByTagName an
array?
Answer:No, a NodeList is not an Array object, although it
can be traversed similarly to an array. It has a length property

Scan to Download
and an item() method to access specific elements, but you
cannot use array methods like push() or reverse() on it.

5.Question
Can you explain the concept of a live NodeList?
Answer:A live NodeList dynamically updates to reflect any
changes made to the document after it has been retrieved. For
instance, if you retrieve a list of <img> elements and then
add more <img> elements to the document, the length of the
NodeList will reflect the new total number of <img>
elements immediately. This behavior can be demonstrated in
a program that tracks the number of <img> elements before
and after new images are added.
Chapter 11 | 2.6. Accessing All Images in a Page|
Q&A
1.Question
What is the purpose of using
document.getElementsByTagName() in JavaScript?
Answer:The method is used to access all elements of
a particular tag type, in this case 'img', returning a
live collection (NodeList) that reflects the current

Scan to Download
state of the document.

2.Question
How can the length of the NodeList be affected after it's
created?
Answer:The NodeList is live, meaning that if new elements
are added to the document after the NodeList is created, its
length property will automatically update to reflect the newly
added elements.

3.Question
Can you traverse the NodeList like an array?
Answer:Yes, the NodeList can be traversed in a manner
similar to an array using a for loop, but since it's not an actual
Array object, Array methods like push() or reverse() cannot
be used on it.

4.Question
What happens when new img elements are added to the
document after retrieving the NodeList?
Answer:The length of the NodeList increases automatically,
demonstrating that it is a live collection which updates
dynamically with the document.

Scan to Download
5.Question
Could you provide an example of how to utilize the
document.getElementsByTagName() method?
Answer:Certainly! You can access all img elements like this:
const imgElements =
document.getElementsByTagName('img'); After this, using a
loop like 'for (let i = 0; i < imgElements.length; i++)' allows
you to interact with each individual img element in the
document.

6.Question
What is the key difference between a NodeList and an
Array in JavaScript?
Answer:The key difference is that a NodeList is a live
collection that directly reflects changes in the document,
whereas an Array is static and does not automatically update
or reflect any changes made to its original data.

7.Question
How does the NodeList's live collection feature benefit
developers?
Answer:This feature allows developers to manipulate the

Scan to Download
DOM without needing to re-query the document for updated
counts or collections, simplifying the task of managing
dynamic content.

8.Question
What property and method do you use to access an
element at a specific index in a NodeList?
Answer:You use 'length' to get the number of elements in the
NodeList and the 'item()' method to access an element at a
specific index.

9.Question
In the presented example, how does the script
demonstrate the NodeList's dynamic nature?
Answer:The script first logs the length of the img NodeList,
adds a new img element to the document, and logs the length
again, illustrating that the length increases from 3 to 4 after
the addition.

10.Question
Why might developers choose to use
getElementsByTagName instead of other selection
methods?

Scan to Download
Answer:Developers may prefer getElementsByTagName for
its ability to access a live collection of elements which is
especially useful for applications where the document
structure may change dynamically.
Chapter 12 | 2.7. Discovering All Images in Articles
Using the Selectors API| Q&A
1.Question
How can I efficiently select all images within article
elements using JavaScript?
Answer:You can efficiently select all <img> elements
within <article> elements using the Selectors API.
The specific command is:

```javascript
const imgs = document.querySelectorAll('article
img');
```

This command will return a NodeList of all the


<img> elements that are descendants of any

Scan to Download
<article> element, allowing for efficient targeting
without unnecessary looping.

2.Question
What is the difference between querySelector() and
querySelectorAll()?
Answer:The difference is that `querySelector()` returns only
the first element that matches the CSS selector, while
`querySelectorAll()` returns a NodeList of all matching
elements. For example:

```javascript
const firstImg = document.querySelector('article img'); //
returns the first <img>
const allImgs = document.querySelectorAll('article img'); //
returns all <img> elements in articles
```

3.Question
What if I need to get only direct child <img> elements of
an <article>?

Scan to Download
Answer:To select only the direct children <img> elements of
an <article>, you can use the greater than (>) combinator in
your selector like this:

```javascript
const imgs = document.querySelectorAll('article > img');
```

This will only select <img> elements that are direct children
of <article> elements.

4.Question
How can I specify conditions on attributes, such as
selecting images with non-empty alt attributes?
Answer:You can use attribute selectors for this purpose. For
images with a non-empty alt attribute, you would do:

```javascript
const imgs = document.querySelectorAll('img:not([alt=""])');
```

Scan to Download
This uses the negation pseudo-class `:not()` to filter out
<img> elements that have an empty alt attribute.

5.Question
Why shouldn’t I use querySelectorAll() for every element
retrieval?
Answer:While `querySelectorAll()` is powerful, it may not
always be the most efficient option. For example, if you need
to select a single element by its ID, use `getElementById()`
instead, as it is optimized for that task and doesn't require
parsing a selector string.

6.Question
What method should I use to add or replace a style for an
element in JavaScript?
Answer:To add or replace a CSS property of an element, you
can use:

```javascript
elem.style.propertyName = 'value'; // Example:

Scan to Download
elem.style.backgroundColor = 'red';
```

If you want to set multiple styles at once, you can use


`setAttribute()` to set the entire style string:

```javascript
elem.setAttribute('style', 'background-color: red; color:
white;');
```

For complex cases, modifying the class of the element can


also be a good strategy.

7.Question
How can I insert a new paragraph before a specific one in
the document?
Answer:To insert a new paragraph just before the third
paragraph within a specific <div>, you can do:

Scan to Download
```javascript
const div = document.getElementById('target');
const paras = div.getElementsByTagName('p');
const newPara = document.createElement('p');
newPara.textContent = 'New paragraph content';

if (paras[2]) {
div.insertBefore(newPara, paras[2]);
} else {
div.appendChild(newPara);
}
```

This checks if a third paragraph exists and inserts the new


paragraph accordingly.

8.Question
How can I retrieve the current computed style of an
element?
Answer:To get the current computed style of an element, you

Scan to Download
can use the `getComputedStyle()` method like this:

```javascript
const style = window.getComputedStyle(elem);
```

This will return all styles applied to the element, taking into
account both directly set styles and styles applied via CSS.

Scan to Download
Chapter 13 | 2.8. Setting an Element’s Style
Attribute| Q&A
1.Question
What are the three methods to modify an element's CSS
properties in JavaScript, and which is the simplest?
Answer:The three methods are: 1) Directly setting
the style property using the element's style property
(e.g., elem.style.backgroundColor = 'red'); 2) Using
setAttribute() to create a complete style string (e.g.,
elem.setAttribute('style', 'background-color: red;
color: white;'); 3) Modifying the class attribute
using class names (e.g., elem.setAttribute('class',
'stripe')). The simplest approach is to directly set the
style property.

2.Question
How do you handle CSS properties that include hyphens
when changing styles in JavaScript?
Answer:When dealing with CSS properties that contain
hyphens, such as 'background-color', you use CamelCase
notation. For example, 'background-color' is written as

Scan to Download
'backgroundColor' in JavaScript.

3.Question
What is the importance of using getComputedStyle and
when would you use it?
Answer:getComputedStyle is essential because it retrieves
the computed styles of an element, merging all styles applied
via stylesheets, inline styles, and default styles. This makes it
useful for determining an element's effective styles at any
given time.

4.Question
What does the createAttribute method do in JavaScript,
and when should it be used?
Answer:The createAttribute method allows you to create a
new attribute node, enabling more complex scenarios such as
working with XML where you might need an attribute value
to reference another entity. For most simple cases, directly
using setAttribute is preferred.

5.Question
Explain how to insert a new paragraph before the third
paragraph in an HTML div element using JavaScript.

Scan to Download
Answer:To insert a new paragraph before the third paragraph
within a div, first access the div using getElementById.
Retrieve the paragraphs with getElementsByTagName.
Create a new paragraph element using createElement, add
text with createTextNode, and append that text to the new
paragraph element. Check if a third paragraph exists; if it
does, use insertBefore to place the new paragraph before the
third one. If it does not exist, simply append the new
paragraph to the end of the div.

6.Question
Why is it important to check for the existence of the third
paragraph before inserting the new one?
Answer:Checking for the existence of the third paragraph
ensures that you don't attempt to insert before a non-existent
element, which would result in an error. This check allows
the script to append to the end of the div if there are fewer
than three paragraphs.
Chapter 14 | 2.9. Inserting a New Paragraph| Q&A
1.Question

Scan to Download
What is the main goal of the solution provided in the
chapter?
Answer:To insert a new paragraph just before the
third paragraph within a div element.

2.Question
How do you retrieve the target paragraph to modify in
the DOM?
Answer:You retrieve the collection of paragraphs located
within the target div using the getElementsByTagName()
method.

3.Question
What JavaScript methods are used to create and insert
the new paragraph?
Answer:The createElement() method is used to create the
new paragraph, and the insertBefore() method is used to
insert it before the existing third paragraph.

4.Question
What happens if the third paragraph does not exist?
Answer:If the third paragraph does not exist, the new
paragraph is appended to the end of the div element using

Scan to Download
appendChild().

5.Question
Why is checking for the existence of the third paragraph
crucial?
Answer:It ensures that the new paragraph is correctly placed
before an existing one if that position is available,
maintaining the intended order in the document.

6.Question
Can you explain the significance of the createElement()
method in this context?
Answer:The createElement() method allows developers to
dynamically create new HTML elements in the DOM,
providing flexibility in modifying the page content without
needing to reload or change the HTML static structure.

7.Question
What underlying concept about DOM manipulation does
this solution illustrate?
Answer:It illustrates the concept of direct DOM
manipulation, where JavaScript is used to add, remove, or
rearrange elements in the document as needed, showcasing

Scan to Download
the interactivity of web applications.

8.Question
How does this chapter connect to the broader themes of
web development?
Answer:This chapter highlights the importance of
understanding and utilizing basic DOM operations, which is
fundamental for creating dynamic and interactive web
pages—essential skills for any web developer.

9.Question
What practical applications can arise from effectively
using DOM methods discussed in this chapter?
Answer:Practical applications include creating responsive
user interfaces, updating content dynamically based on user
interaction, and enhancing user experience through real-time
changes to web page elements without a full page refresh.

Scan to Download
JavaScript Cookbook Quiz and Test
Check the Correct Answer on Bookey Website

Chapter 1 | 1.1. Using Errors| Quiz and Test


1.JavaScript has an undefined number of Error
subtypes, including `EvalError`, `TypeError`, and
`SyntaxError`.
2.To create a custom error type in JavaScript, you need to
subclass the Error class using ECMAScript 2015 syntax.
3.When throwing a RangeError, it is recommended to
provide uninformative messages to avoid disturbing user
experience.
Chapter 2 | 1.2. Capturing Errors by their subtypes|
Quiz and Test
1.JavaScript features seven subtypes of Error that
can help identify the nature of an error in code.
2.The SyntaxError subtype is raised by issues with `eval()`.
3.Creating custom error types in JavaScript can be done
through subclassing existing error types.
Chapter 3 | 1.3. Throwing useful errors| Quiz and

Scan to Download
Test
1.JavaScript has several Error subtypes, including
TypeError and RangeError, which help express
incorrect states within applications.
2.TypeError should be used for values that are out of
acceptable ranges.
3.Creating custom error subtypes is unnecessary since
standard Error types cover all cases.

Scan to Download
Chapter 4 | 1.4. Throwing custom errors| Quiz and
Test
1.Custom error types can be created using
ECMAScript 2015 class syntax in JavaScript.
2.The only error type that can be subclassed for JSON
parsing in JavaScript is the built-in Error type.
3.The `betterParse` function is used to improve error
handling when parsing JSON strings.
Chapter 5 | 1.5. Handling JSON parsing errors|
Quiz and Test
1.Parsing JSON errors always raise a specific
SyntaxError that clearly indicates the issue.
2.The JSONParseError class is used to provide more
informative error logging during JSON parsing.
3.The betterParse function does not handle errors during
JSON parsing and directly returns the result of
JSON.parse().
Chapter 6 | 2.1. Accessing a Given Element and
Finding Its Parent and Child Elements| Quiz and
Test

Scan to Download
1.The method document.getElementById() is used to
retrieve a specific web page element and can
return null if the element does not exist.
2.The childNodes property only returns the direct child
elements of an element, excluding text nodes.
3.Modern browsers support the forEach() method for
NodeLists, but it is not available in Internet Explorer
without a polyfill.

Scan to Download
Chapter 7 | 2.2. Traversing the Results from
querySelectorAll() with forEach()| Quiz and Test
1.You can use forEach() with a NodeList in modern
browsers, including Internet Explorer.
2.The method parseFloat() can be used to convert strings to
numbers when summing values in an HTML table.
3.querySelectorAll() returns an Array of nodes when called.
Chapter 8 | 2.3. Adding Up Values in an HTML
Table| Quiz and Test
1.The `parseInt()` method is preferred over
`parseFloat()` for converting numeric strings in an
HTML context.
2.The sum of values in a specific column of an HTML table
can be calculated using `document.querySelectorAll()` to
select cells.
3.It is necessary to create a new table row to display the sum
after calculating it.
Chapter 9 | 2.4. Problem| Quiz and Test
1.To sum all numeric values present in a specific
column of an HTML table, you must initialize a

Scan to Download
sum variable first.
2.The function `parseInt()` should be used instead of
`parseFloat()` to handle both integers and floating numbers
in column sums.
3.It is not possible to append a new row summarizing the
total to an HTML table after calculating the sum.

Scan to Download
Chapter 10 | 2.5. Finding All Elements That Share
an Attribute| Quiz and Test
1.The universal selector can be used to find all
elements with a specific attribute regardless of its
value.
2.The method 'getElementsByTagName()' returns a static
NodeList of the specified element type.
3.You can use the selector ':not' to find elements that do not
have a certain class.
Chapter 11 | 2.6. Accessing All Images in a Page|
Quiz and Test
1.The method document.getElementsByTagName()
can be used to access all img elements in a
document.
2.A NodeList is an Array object and supports Array methods
such as push() and reverse().
3.The NodeList returned by
document.getElementsByTagName() is a static collection
that does not update with changes in the document.

Scan to Download
Chapter 12 | 2.7. Discovering All Images in Articles
Using the Selectors API| Quiz and Test
1.The Selectors API includes the method
`querySelector()` which returns all matching
elements.
2.To change a specific style of an element, you can use the
`style` property of that element.
3.The `createElement()` method can be used to create new
HTML elements in the DOM.

Scan to Download
Chapter 13 | 2.8. Setting an Element’s Style
Attribute| Quiz and Test
1.You can modify a single CSS property directly by
accessing the element's style property in
JavaScript.
2.Using setAttribute() to modify CSS properties will retain
previously set values if you only change one property.
3.To insert a new paragraph before the third paragraph, you
need to check if the third paragraph exists first.
Chapter 14 | 2.9. Inserting a New Paragraph| Quiz
and Test
1.The `createElement()` method can generate a new
HTML element to be inserted into a document.
2.The `insertBefore()` method can only be used to append
new elements to the end of a parent element.
3.If there is no third paragraph in a div, the new paragraph
will be inserted before the third paragraph.

Scan to Download

You might also like