JavaScript Cookbook: Programming the Web 3rd Edition Scott instant download
JavaScript Cookbook: Programming the Web 3rd Edition Scott instant download
https://textbookfull.com/product/javascript-cookbook-programming-
the-web-3rd-edition-scott/
https://textbookfull.com/product/web-api-cookbook-level-up-your-
javascript-applications-joe-attardi/
https://textbookfull.com/product/javascript-object-programming-
rinehart-martin/
https://textbookfull.com/product/essential-asp-net-web-forms-
development-full-stack-programming-with-c-sql-ajax-and-
javascript-1st-edition-robert-e-beasley/
Learning JavaScript 3rd Edition Ethan Brown
https://textbookfull.com/product/learning-javascript-3rd-edition-
ethan-brown/
https://textbookfull.com/product/web-applications-with-elm-
functional-programming-for-the-web-1st-edition-wolfgang-loder/
https://textbookfull.com/product/reactive-programming-with-
javascript-1st-edition-hayward-jonathan/
https://textbookfull.com/product/python-network-programming-
cookbook-kathiravelu/
https://textbookfull.com/product/python-gui-programming-cookbook-
meier/
1. 1. Errors
1. 1.1. Using Errors
2. 1.2. Capturing Errors by their subtypes
3. 1.3. Throwing useful errors
4. 1.4. Throwing custom errors
5. 1.5. Handling JSON parsing errors
2. 2. Working with HTML
1. 2.1. Accessing a Given Element and Finding Its
Parent and Child Elements
2. 2.2. Traversing the Results from querySelectorAll()
with forEach()
3. 2.3. Adding Up Values in an HTML Table
4. 2.4. Problem
5. 2.5. Finding All Elements That Share an Attribute
6. 2.6. Accessing All Images in a Page
7. 2.7. Discovering All Images in Articles Using the
Selectors API
8. 2.8. Setting an Element’s Style Attribute
9. 2.9. Inserting a New Paragraph
JavaScript Cookbook
THIRD EDITION
With Early Release ebooks, you get books in their earliest form—the author’s
raw and unedited content as they write—so you can take advantage of these
technologies long before the official release of these titles.
See http://oreilly.com/catalog/errata.csp?isbn=9781491901885
for release details.
While the publisher and the authors have used good faith
efforts to ensure that the information and instructions
contained in this work are accurate, the publisher and the
authors disclaim all responsibility for errors or omissions,
including without limitation responsibility for damages resulting
from the use of or reliance on this work. Use of the information
and instructions contained in this work is at your own risk. If
any code samples or other technology this work contains or
describes is subject to open source licenses or the intellectual
property rights of others, it is your responsibility to ensure that
your use thereof complies with such licenses and/or rights.
978-1-492-05568-6
Chapter 1. Errors
A NOTE FOR EARLY RELEASE READERS
With Early Release ebooks, you get books in their earliest form—the author’s raw and unedited
content as they write—so you can take advantage of these technologies long before the official
release of these titles.
This will be the fourth chapter of the final book. Please note that the GitHub repo will be made
active later on.
Solution
Create an instance of Error, or a subtype, throw it, and catch it
later on. Perhaps that is too brief a description. Start by
creating an instance of Error. The constructor takes a string as
an argument. Pass something useful and indicative of what the
problem was. Consider keeping a list of the various error
strings used in the application so that they are consistent and
informative. Use the throw keyword to throw the instance you
created. Then catch it in a try-catch block.
function willThrowError() {
if ( /* something goes wrong */) {
// Create an error with useful information.
// Don't be afraid to duplicate something
from the stack trace, like the method name
throw new Error(`Problem in ${method},
${reason}`);
}
}
try {
willThrowError();
// Other code will not be reached
} catch (error) {
console.error('There was an error: ', error);
}
Discussion
We can create an error either with the new keyword before the
Error or not. If Error() is called without new preceding it,
Error() acts as a function which returns an Error object. The
end result is the same. The Error constructor takes one
standard argument: the error message. This will be assigned to
the error’s message property. Some engines allow for
additional non-standard arguments to the constructor, but
these are not part of a current ECMAScript spec and are not on
track to be on a future one. Wrapping the code that will throw
an error in a try-catch block allows us to catch the error
within our code. Had we not done so, the error would have
propagated to the top of the stack and exited JavaScript. Here,
we are reporting the error to the console with
console.error. This is more or less the default behavior,
though we can add information as part of the call to
console.error.
Problem
How do we catcn errors by their subtype?
Solution
In your catch block, check the specific error type
try {
// Some code that will raise an error
} catch (err) {
if (err instanceof RangeError) {
// Do something about the value being out of
range
} else if (err instanceof TypeError) {
// Do something about the value being the
wrong type
} else {
// Rethrow the error
throw err;
}
}
Discussion
We may need to respond to specific subtypes of Error. Perhaps
the subtype can tell us something about what went wrong with
the code. Or maybe our code threw a specific Error subtype on
purpose, to carry additional information about the problem in
our code. Both TypeError and RangeError lend themselves to
this behavior, for example. The problem is that JavaScript
permits only one catch block, offering neither opportunity nor
syntax to capture errors by their type. Given JavaScript’s
origins, this is not surprising, but it is nonetheless
inconventient.
Our best option is to check the type of the Error ourselves. Use
an if statement with the instanceof operator to check the
type of the caught error. Remember to write a complete if-else
statement, otherwise your code may accidentally swallow the
error and suppress it. In the code above, we assume that we
cannot do anything useful with error types that are neither
RangeErrors nor TypeErrors. We re-throw other errors, so that
code higher up the stack than this can choose to capture the
error. Or, as is appropriate, the error could bubble to the top of
the stack, as it normally would.
Problem
You want to throw useful Error subtypes
Solution
Use TypeError to express an incorrect parameter or variable
type
function calculateValue(x) {
if (typeof x !== 'number') {
throw new TypeError(`Value [${x}] is not a
number.`);
}
Discussion
If you are going to use Errors to express incorrect states for
your application, the TypeError and RangeError hold some
promise. TypeError covers issues where the expected value
was of the wrong type. What constitutes a “wrong” type?
That’s up to us as the designers. Our code might expect one of
JavaScript’s “primitive” values returned by a call to typeof. If
our function receives an unantipated value type, we could
throw a TypeError. We can say the same with instanceof for
object types. These are not hard limits on when we might
throw a TypeError, but they are good guidelines.
Problem
How do we create our own Error subtypes?
Solution
Create a subtype of Error by subclassing Error using the
ECMAScript 2015 class inheritance syntax
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CustomError);
}
this.name = 'CustomError';
this.customProp = customProp;
}
}
Discussion
When subclassing Error, we should keep in mind two possibly
competing concerns: stayign within the bounds of a typical
JavaScript error, and expressing enough information for our
customized error. In the former case, do not attempt to
recreate the errors or exceptions of your second favorite
language. Do not over-extend JavaScript’s Error type with extra
methods and properties. A later programmer using your new
Error subtype should be able to make reasonable assumptions
about the subtype’s API. They should be able to access
standard information in the standard way.
Problem
How should we handle parsing of bad or malformed JSON
data?
Solution
Create a custom subtype of SyntaxError which is raised on
issues with JSON parsing.
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;
}
}
}
Discussion
We would like to log a specific error type when JSON.parse
encounters an error. We can create a class,
JSONParseError, which is a subclass of SyntaxError, for
problems with JSON parsing. The class itself does not do
much, other than establishing the name and type
JSONParseError. But consumers of this API can now test for
JSONParseError as opposed to the too-general SyntaxError.
Logging will improve as well.
This will be the thirteenth chapter of the final book. Please note that the GitHub repo will be
made active later on.
Problem
You want to access a specific web page element, and then find
its parent and child elements.
Solution
Give the element a unique identifier:
<div id="demodiv">
<p>
This is text.
</p>
</div>
Discussion
A web document is organized like an upside-down tree, with
the topmost element at the root and all other elements
branching out beneath. Except for the root element (HTML),
each element has a parent node, and all of the elements are
accessible via the document.
NOTE
There are numerous ways to get one specific web page element,
including the use of selectors, covered later in the chapter. But
you’ll always want to use the most restrictive method possible,
and you can’t get more restrictive than
document.getElementById().
const parent =
document.getElementById("demodiv").parentNode;
You can find out the type of element for each node through
the nodeName property:
If you want to find out what children an element has, you can
traverse a collection of them via a NodeList, obtained using the
childNodes property:
if (demodiv.hasChildNodes()) {
const children = demodiv.childNodes;
children.forEach(child => {
outputString += `has child ${child.nodeName}
`;
});
}
console.log(outputString);;
VILLÉGIATURE.—LE TRÉSOR.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com