Instant Access to JavaScript Cookbook: Programming the Web 3rd Edition Scott ebook Full Chapters
Instant Access to JavaScript Cookbook: Programming the Web 3rd Edition Scott ebook Full Chapters
com
https://textbookfull.com/product/javascript-cookbook-
programming-the-web-3rd-edition-scott/
OR CLICK BUTTON
DOWNLOAD NOW
https://textbookfull.com/product/web-api-cookbook-level-up-your-
javascript-applications-joe-attardi/
textboxfull.com
https://textbookfull.com/product/javascript-object-programming-
rinehart-martin/
textboxfull.com
https://textbookfull.com/product/learning-javascript-3rd-edition-
ethan-brown/
textboxfull.com
https://textbookfull.com/product/web-applications-with-elm-functional-
programming-for-the-web-1st-edition-wolfgang-loder/
textboxfull.com
https://textbookfull.com/product/reactive-programming-with-
javascript-1st-edition-hayward-jonathan/
textboxfull.com
https://textbookfull.com/product/python-network-programming-cookbook-
kathiravelu/
textboxfull.com
https://textbookfull.com/product/python-gui-programming-cookbook-
meier/
textboxfull.com
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);;
The best way to see how messy the DOM can be is to use a
debugger such as the Firefox or Chrome developer tools,
access a web page, and then utilize whatever DOM inspection
tool the debugger provides. I opened a simple page in Firefox
and used the developer tools to display the element tree, as
shown in Figure 2-1.
Figure 2-1. Examining the element tree of a web page using Firefox’s
developer tools
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() when working
with a NodeList (the collection returned by
querySelectorAll()):
items.forEach(item => {
console.log(item.firstChild.data);
});
Discussion
forEach() is an Array method, but the results of
querySelectorAll() is a NodeList which is a different type
of object than an Array. Thankfully, modern browsers have
built in support for forEach, allowing us to iterate over a
NodeList like an array.
Another Random Scribd Document
with Unrelated Content
The Project Gutenberg eBook of Stepping
stones to manhood
This ebook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this ebook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.
Language: English
MANHOOD
A BOOK of INSPIRATION
for BOYS and YOUNG MEN
By WILLIAM P. PEARCE
AUTHOR OF “THE MASTER’S GREATEST MONOSYLLABLES,” “THE
TABERNACLE,” “THE MASTER’S LOVE,” ETC., ETC.
PHILADELPHIA:
HARPER & BROTHER COMPANY
1903
COPYRIGHT, 1903,
BY
HARPER & BROTHER COMPANY.
TO
WESLEY P. PEARCE
MY SON
AND TO THE
CHAPTER.
1. Robert J. Burdette. One of America’s moral humorists.
2. Adolph Sutro. Former mayor of San Francisco.
3. Joshua Levering. A noted Christian business man.
4. O. O. Howard. General during the Civil War.
5. Booker T. Washington. The foremost colored educator and
orator of the day.
6. J. T. Rich. A beloved Governor of Michigan.
7. George S. Cull. The author’s instructor during boyhood.
8. George W. Bain. Colonel in the Civil War, and a temperance
orator.
9. Asa Clark, M. D. Supt. State Insane Asylum, Stockton,
California.
10. Marshall Field. One of Chicago’s most honored and
prosperous business men.
11. T. T. Geer. Governor of Oregon.
12. F. W. Warren. Member of the United States Senate.
13. Aaron S. Zook. A widely known lawyer and lecturer.
14. George T. Angell. President and founder of the American
Humane Educational Society.
15. Thomas J. Morgan. General in Civil War, Commissioner of
Indian affairs under President Harrison.
16. Neal Dow. Former Governor of Maine. The “Grand Old Man”
of temperance.
17. H. H. Hadley. Colonel in Civil War. General of the Inter-State
Blue Ribbon Army.
18. Anthony Comstock. Secretary of the New York Society for the
Suppression of Vice.
19. Lyman J. Gage. A prominent banker and a member of
President McKinley’s cabinet.
20. John Clark Ridpath. Historian of the United States.
21. Samuel Fallows. Bishop Reformed Episcopal Church.
22. George C. Lorimer. Minister, author and lecturer.
23. James H. Brookes. An able Bible expositor and writer.
24. Wilbur F. Crafts. A noted defender of the Lord’s Day.
25. Wayland Hoyt. A writer and preacher of prominence.
26. C. C. McCabe. Bishop of the M. E. Church.
27. H. H. Warren. An eminent clergyman.
28. Warren Randolph. A minister of prominence.
29. H. L. Hastings. Editor and preacher.
30. Opie Rodway. Evangelist to whom the author owes much.
PREFACE.
Boyhood is one of the happiest periods of life. “Ye little know,” said
Robert Burns, “the ill ye court when manhood is your wish.” Taking a
look backward Lord Byron cried, “Ah, happy years once more, who
would not be a boy?” Thomas Moore says, in his beautiful poem: “Oft
in the Stilly Night:”
“The smiles, the tears of boyhood’s years,
The words of love then spoken;
The eyes that shone now dimmed and gone,
The cheerful hearts now broken!
INTRODUCTION TO CHAPTER I
By Robert J. Burdette
You can make yourself look an inch taller by neat, well-fitting dress.
You can actually make yourself taller by an erect, manly carriage.
Slovenliness is contagious. It communicates itself from the dress to
the character. The boy who slouches and slumps in figure and gait, is
dangerously apt to slump morally. The dust and grime on your
clothes is liable to get into your brain. The dirt under your finger-
nails is likely to work into your thoughts. Grease spots down the
front of your coat will destroy self-respect almost as quickly as a
habit of lying. Tidiness is one of the cheapest luxuries in the world. It
is also one of the most comfortable. When you know, when you are
“dead sure” that you are just right—“perfectly correct”—from hat to
shoe-tie, the King of England couldn’t stare you out of countenance;
he couldn’t embarrass you, and, he wouldn’t if he could.
CHAPTER I
Be Neat
A high column was to be built. The workmen were engaged, and all
went to work with a will. In laying a corner, one brick was set a trifle
out of line. This was unnoticed, and as each course of bricks was kept
in line with those already laid, the tower was not built exactly erect.
After being carried up about fifty feet, there was a tremendous crash.
The building had fallen, burying the men in the ruins. All the
previous work was now lost, the material wasted, and several
valuable lives sacrificed, all through the misplacement of one brick at
the start. The workman at fault little thought what mischief he was
making for the future. It is so with the boy, building character. He
must be careful in laying the foundation. Just so far as he governs,
guards and trains himself, just so far will he succeed or fail in the
estimation of others. Tennyson wisely wrote:
“Self-reverence, self-knowledge, self-control,
These three alone lead life to sovereign power.”
AMERICAN BOYS.
Never in the history of any people did boys have so much in their
favor to assist them in reaching the pinnacle of success as American
boys. Back of them is an ancestry of the best blood of the leading
nations of the world, an ancestry noted for persistence, reverence,
piety and patriotism.
The educational institutions of the land have “turned out”
thousands of young men who have beaten their pathway upward in
spite of adverse circumstances, all of which seems to say to the boy
to-day, “There’s room at the top in whatever profession you may
follow.” A good beginning is the most necessary thing, for “it is half
the battle.” In any race a man can well afford to miss applause at the
starting-line, if he gets it at the goal. A slow but determined start is
not incompatible with a swift conclusion. Experienced mountain-
climbers seem almost lazy, so calmly do they put one foot in front of
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
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