100% found this document useful (2 votes)
75 views

Instant Access to JavaScript Cookbook: Programming the Web 3rd Edition Scott ebook Full Chapters

Programming

Uploaded by

kusholsekhor
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
75 views

Instant Access to JavaScript Cookbook: Programming the Web 3rd Edition Scott ebook Full Chapters

Programming

Uploaded by

kusholsekhor
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Experience Seamless Full Ebook Downloads for Every Genre at textbookfull.

com

JavaScript Cookbook: Programming the Web 3rd


Edition Scott

https://textbookfull.com/product/javascript-cookbook-
programming-the-web-3rd-edition-scott/

OR CLICK BUTTON

DOWNLOAD NOW

Explore and download more ebook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Web API Cookbook Level Up Your JavaScript Applications Joe


Attardi

https://textbookfull.com/product/web-api-cookbook-level-up-your-
javascript-applications-joe-attardi/

textboxfull.com

JavaScript Learn JavaScript in 24 Hours or Less A Beginner


s Guide To Learning JavaScript Programming Now JavaScript
JavaScript Programming 1st Edition Robert Dwight.
https://textbookfull.com/product/javascript-learn-javascript-
in-24-hours-or-less-a-beginner-s-guide-to-learning-javascript-
programming-now-javascript-javascript-programming-1st-edition-robert-
dwight/
textboxfull.com

JavaScript Object Programming Rinehart Martin

https://textbookfull.com/product/javascript-object-programming-
rinehart-martin/

textboxfull.com

Essential ASP.NET Web Forms Development: Full Stack


Programming with C#, SQL, Ajax, and JavaScript 1st Edition
Robert E. Beasley
https://textbookfull.com/product/essential-asp-net-web-forms-
development-full-stack-programming-with-c-sql-ajax-and-javascript-1st-
edition-robert-e-beasley/
textboxfull.com
Learning JavaScript 3rd Edition Ethan Brown

https://textbookfull.com/product/learning-javascript-3rd-edition-
ethan-brown/

textboxfull.com

Web Applications with Elm: Functional Programming for the


Web 1st Edition Wolfgang Loder

https://textbookfull.com/product/web-applications-with-elm-functional-
programming-for-the-web-1st-edition-wolfgang-loder/

textboxfull.com

Reactive Programming with JavaScript 1st Edition Hayward


Jonathan

https://textbookfull.com/product/reactive-programming-with-
javascript-1st-edition-hayward-jonathan/

textboxfull.com

Python Network Programming Cookbook Kathiravelu

https://textbookfull.com/product/python-network-programming-cookbook-
kathiravelu/

textboxfull.com

Python GUI Programming Cookbook Meier

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.

John Paxton, Adam D. Scott, and Shelley Powers


JavaScript Cookbook, 3E

By John Paxton, Adam D. Scott, and Shelley Powers

Copyright © 2021 John Paxton, Adam Scot, Shelley Powers. All


rights reserved.

Printed in the United States of America.

Published by O’Reilly Media, Inc., 1005 Gravenstein Highway


North, Sebastopol, CA 95472.

O’Reilly books may be purchased for educational, business, or


sales promotional use. Online editions are also available for
most titles (http://oreilly.com). For more information, contact
our corporate/institutional sales department: 800-998-9938 or
[email protected].

Editors: Simon St. Laurent and Brian MacDonald

Production Editor: Kara Ebrahim

Copyeditor: Jasmine Kwityn

Proofreader: Kara Ebrahim

Indexer: Judy McConville

Interior Designer: David Futato

Cover Designer: Ellie Volckhausen


Illustrator: Rebecca Demarest
July 2010: First Edition

February 2015: Second Edition

November 2020: Third Edition

Revision History for the Early Release


2020-06-03: First release

See http://oreilly.com/catalog/errata.csp?isbn=9781491901885
for release details.

The O’Reilly logo is a registered trademark of O’Reilly Media,


Inc. JavaScript Cookbook, 2E, the cover image, and related
trade dress are trademarks of O’Reilly Media, Inc.

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.

Errors. Everyone has them. No one is perfect. Things go


wrong. Sometimes the error could have been anticipated, other
times, not so much. To modify a cliche, it’s not so much the
error as what you do with it that matters.

What should we do with our errors, then? The default behavior


is for JavaScript to die at the point of the error, exiting with a
stack trace. We can capture an error, react to it, modify it, re-
throw it, even hide it if we choose. Returning to a theme of
this cookbook: just because we can, does not mean we should.
Our guiding light is effective, efficient, reusable JavaScript
programming. Let’s look at Errors under this light.

JavaScript is not robust at error handing in general. The


language has the Error object, which is flexible enough. But
catching errors with try-catch lacks features found in other
languages. We cannot catch errors by their type. We cannot
(easily) filter by error. Further, in the browser, it is rare that we
can recover from an error. Rare enough that the recipes below
deal with the few common error situations from which an
application can recover. In Node.js, throwing errors causes
enough problems that an entirely different pattern of error
handling involed. We will look at Node’s peculiar form of error
“handling” as well.

Our goal should be to make our programming experience


better. Instead of our JavaScript engine dying horribly with an
incomprehensible error, we can add and modify information
about the error, illuminating the path for the person (likely
ourselves) tasked with fixing the error. Allow the failure to
happen, but clarify why the error occurred and who raised it.

1.1 Using Errors


JavaScript has eight Error types. The parent type is the aptly-
named Error. There are seven subtypes, which we will look
at in the next recipe. What does an Error give us? We can
count on three properties: a constructor, name, and message.
These are all available to subclasses of Error as well. We also
have access to a toString() method which will usually
return the message property. If we are using the V8
JavaScript engine (Chrome, Node.js, possibly others), we can
use captureStackTrace() as well. More on this soon. Let’s
start with a standard JavaScript Error object.
Problem
You want to create, throw, and catch a standard error

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}`);
}
}

// Somewhere else in your code

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.

1.2 Capturing Errors by their subtypes


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. This may illuminate the possibility of
recovery, or at least give us a little more information about
what went wrong.

The seven Error subtypes:

EvalError: thrown by use of the built-in function eval()

InternalError: Internal to the JavaScript engine; not part of


the ECMAScript spec, but used by engines for non-standard
errors

RangeError: A value is outside of its valid range

ReferenceError: Raised when encountering a problem trying


to dereference an invalid reference

SyntaxError: A problem with the syntax of evaluated code,


including JSON

TypeError: A variable or parameter is of an unexpected or


wrong type

URIError: Raised by problems with encodeURI() and


decodeURI()

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.

We should note: handling errors, even by their subtype, is


fraught with difficulties in JavaScript. With rare exceptions, an
error raised by your JavaScript engine cannot be recovered
from in a meaningful sense. It is better to try to bring useful
information about the error to the attention of the user, rather
than to try to bring JavaScript back into a correct state (which
may, in fact, be impossible!).

For example: Consider an EvalError. What are we, as coders,


going to do if there’s an EvalError or a SyntaxEror? It seems
that we should go an fix our code. What about a
ReferenceError? Code cannot recover from trying to
dereference an invalid referent. We might be able to write a
catch block that returns something more informative than
“Attempted to call getFoo() on undefined”. But we cannot
determine what the original code intended. We can only
repackage the error and exit gracefully (if possible). In the
next section, we will look at two error types that offer the
possibility of recovery, as well as throwing our own, more
useful error types.

1.3 Throwing useful errors


Given the limits of JavaScript and error handling, are there
Error subtypes worth using? Several of the subtypes of Error
are limited to very specific cases. But two, the RangeError, and
the TypeError show some promise.

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.`);
}

// Rest of the function


}

Use RangeError to express that a parameter or value is out of


range
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 of ${lower} to ${upper}.`);
}
}

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.

Going further, if our function received the right kind of value


but it was outside of an acceptable range, we can throw a
RangeError. Note that RangeErrors are specifically bound to
numeric values. Put another way, we should not throw a
RangeError when expecting a string and receiving one that is
too short or too long. In the case of either RangeErrors or
TypeErrors, make sure your error message is informative.
Include the given value and information about the expected
value.

Do not use errors for to validate forms or other input. Errors


often do not show up in the HTML of a page, as they are re-
routed to the console. Even if they do show up in the visible
part of the page, they often contain impenetrable and weird
content which will confuse and annoy the common user. And if
they are not anticipated as part of your rendered content, they
can throw off the rendering of the rest of the view. Invalid user
data should be an expected state of your code, and should be
handled in a user-friendly manner. There are both native APIs
for form validation, as well as customizable, event-based hooks
for validation. Use those instead. Errors in JavaScript indicate a
state where your code received input that is just wrong and
should be corrected.

1.4 Throwing custom errors


The Error type might be too broad. Most subclasses are too
specific, or too limiting. What if we want to create our own
Error types? How should we subclass Error?

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

class CustomError extends Error {


constructor(customProp='customValue',
...params) {
super(...params);

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.

Your subclass constructor can take custom properties, which


should be distinct from the standard argument of an error
message. Keep in mind that Firefox and some other browsers
expect the first three arguments to the Error constructor to be
a message string, a filename, and a line number. If your
subclass’s constructor takes custom arguments, add the to the
front of the parameters list. This will make capturing standard
arguments easier, as we can use ECMAScript 2015’s rest
parameter feature to vaccuum up any remaining arguments.

In the constructor for your custom error, call super() first,


passing any standard parameters. Because your code might
run on V8 (either Chrome or Node.js), properly set this Error’s
stack trace. Check for the captureStackTrace method, and,
if present, call Error.captureStackTrace passing it a reference to
the current instance (as this) and your CustomError class.

Set the name property of your custom error subclass. This


ensures that, when reporting to the console, your error will
carry the name of your subclass, instead of the more generic
Error class.

Set any custom properties as necessary.


1.5 Handling JSON parsing errors
JavaScript Object Notation has become a popular, portable
data format thanks in part to the popularity of JavaScript.
There are two native functions availabe for JSON processing:
for JavaScript-to-JSON conversion, use
JSON.stringify(jsObject). To deserialize a JSON string
into a JavaScript object (or string, or array, etc.) use
JSON.parse(jsonString). Conversion of JavaScript to a
JSON string should not raise any errors, barring issues with the
JavaScript engine implementing JSON.stringify. On the
other hand, converting a JSON string into JavaScript has many
potential issues. The JSON could be malformed, or could just
not be JSON at all! JavaScript raises error with JSON parsing as
SyntaxErrors, which is sub-optimal. A SyntaxError is raised
when JavaScript tries to interpret syntactically invalid code.
While technically accurate, this lacks detail in the case of JSON
parsing.

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.

Remembering to re-throw SyntaxErrors as JSONParseErrors


anytime we parse JSON strings is tedious. Instead, we will call
betterParse(jsonString) which does the work for us.
The betterParse function wraps the call to JSON.parse()
in a try block, safely catching any SyntaxErrors. If a
SyntaxError is raised, we will re-package it as a
JSONParseError. 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. Working with
HTML
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 thirteenth chapter of the final book. Please note that the GitHub repo will be
made active later on.

In 1995 Netscape tasked software developer Brendan Eich with


creating a programming language designed for adding
interactivity to pages in the Netscap Navigator browser. In
response, Eich infamously developed the first version of
JavaScript in 10 days. A few years later, JavaScript has became
a cross-browser standard through the adoption of the
ECMAScript standardization.

Despite the early attempt at standardization, web developers


battled for years with browsers that had different JavaScript
engine interpretations or features. Popular libraries, such as
jQuery effectively allowed us to write simple cross-browser
JavaScript. Thankfully, today’s browsers share a near uniform
implementation of the language. Allowing web developers to
write “vanilla” (library-free) JavaScript to interact with an HTML
page.

When working with HTML, we are working with the Document


Object Model (DOM), which is the data representation of the
HTML page. The recipes in this chapter will review how to
interact with the DOM of an HTML page by selecting, updating,
and removing elements from the page.

2.1 Accessing a Given Element and Finding


Its Parent and Child Elements

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>

Use document.getElementById() to get a reference to


the specific element:
const demodiv =
document.getElementById("demodiv");

Find its parent via the parentNode property:

const parent = demodiv.parentNode;

Find its children via the childNodes property:

const children = demodiv.childNodes;

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.

There are several different techniques available for accessing


these document elements, or nodes as they’re called in the
Document Object Model (DOM). Today, we access these nodes
through standardized versions of the DOM, such as the DOM
Levels 2 and 3. Originally, though, a de facto technique was to
access the elements through the browser object model,
sometimes referred to as DOM Level 0. The DOM Level 0 was
invented by the leading browser company of the time,
Netscape, and its use has been supported (more or less) in
most browsers since. The key object for accessing web page
elements in the DOM Level 0 is the document object.

The most commonly used DOM method is


document.getElementById(). It takes one parameter: a
case-sensitive string with the element’s identifier. It returns an
element object, which is referenced to the element if it exists;
otherwise, it returns null.

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().

The returned element object has a set of methods and


properties, including several inherited from the node object.
The node methods are primarily associated with traversing the
document tree. For instance, to find the parent node for the
element, use the following:

const parent =
document.getElementById("demodiv").parentNode;
You can find out the type of element for each node through
the nodeName property:

const type = parent.nodeName;

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:

let outputString = '';

if (demodiv.hasChildNodes()) {
const children = demodiv.childNodes;
children.forEach(child => {
outputString += `has child ${child.nodeName}
`;
});
}
console.log(outputString);;

Given the element in the solution, the output would be:

"has child #text has child P has child #text "

You might be surprised by what appeared as a child node. In


this example, whitespace before and after the paragraph
element is itself a child node with a nodeName of #text. For
the following div element:

<div id="demodiv" class="demo">


<p>Some text</p>
<p>Some more text</p>
</div>

the demodiv element (node) has five children, not two:

has child #text


has child P
has child #text
has child P
has child #text

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()):

// use querySelector to find all list items on a


page
const items = document.querySelectorAll('li');

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.

Title: Stepping stones to manhood


A book of inspiration for boys and young men

Author: William Peter Pearce

Release date: December 24, 2023 [eBook #72500]

Language: English

Original publication: Philadelphia: Harper & Brothers Company,


1903

Credits: Richard Tonsing, Donald Cummings, and the Online


Distributed Proofreading Team at https://www.pgdp.net
(This file was produced from images generously made
available by The Internet Archive/American Libraries.)

*** START OF THE PROJECT GUTENBERG EBOOK STEPPING


STONES TO MANHOOD ***
Transcriber’s Note:
New original cover art included with this eBook is
granted to the public domain.
Stepping Stones to Manhood
STEPPING STONES TO

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.

Linotyped and Printed by


Harper & Brother Company

TO

WESLEY P. PEARCE

MY SON

WHO AFFORDS ME MUCH COMFORT IN THESE HIS BOYHOOD


DAYS

AND TO THE

BOYS OF THIS GREAT NATION

THIS WORK IS LOVINGLY DEDICATED.


CONTENTS.
Part I.—Relation to Self.
CHAPTER. PAGE.
1. Be Neat. 15
2. Be Polite. 23
3. Be Truthful. 33
4. Be Choice of Language. 45
5. Be Ambitious. 55
6. Be Industrious. 67
7. Be Studious. 79
8. Be Temperate. 93
9. Be Free of the Weed. 103
10. Be Persevering. 115

Part II.—Relation to Others.


CHAPTER. PAGE.
11. Be Dutiful. 131
12. Be Honest. 141
13. Be Just. 151
14. Be Kind. 159
15. Be Generous. 171
16. Be Careful of Your Company. 181
17. Be Cautious of Baneful Amusements. 191
18. Be Chary of Bad Books. 201
19. Be Attentive to Details. 213
20. Be Patriotic. 225

Part III.—Relation to God.


CHAPTER. PAGE.
21. Be a Christian. 239
22. Be Prayerful. 249
23. Be a Bible Student. 261
24. Be a Sabbath Observer. 275
25. Be a Church member. 287
26. Be a Worker for Jesus. 299
27. Be a Witness for Jesus. 309
28. Be Loving. 319
29. Be Hopeful. 329
30. Be Faithful. 339
LIST OF THOSE WHO HAVE WRITTEN
INTRODUCTIONS TO CHAPTERS.

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!

“Thus in the stilly night


Ere slumber’s chain has bound me,
Sad mem’ry brings the light
Of other days around me.”

“There is no boy so poor,” said Phillips Brooks, “so ignorant, so


outcast, that I do not stand in awe before him.” “I feel a profounder
reverence for a boy than a man,” said President Garfield. “I never
meet a ragged boy on the street without feeling that I owe him a
salute, for I know not what possibilities may be buttoned up under
his coat.” “Why, bless me! Is that the boy who did so gallantly in
those two battles?” asked President Lincoln as a lad from the
gunboat Ottawa was introduced to him. “Why, I feel as though I
should take off my hat to him, and not he to me.”
“Get out of my way! What are you good for anyhow?” asked a cross
man to a lad who happened to be standing in his way. The boy
replied, “They make men out of such things as I am.” How true. That
dirty boy taken by a philanthropist in New Orleans, only for the
reason that he was an orphan, became Sir Henry M. Stanley, who
found Livingstone and opened Africa. About fifty years ago, when
New York City sought to aid her homeless children, an agent called
on Judge John Green, of Tixston, Indiana, to inquire if he would take
a boy. Mr. Green said, “I will, if you will bring me the raggedest,
dirtiest and ugliest one of the lot.” A boy by the name of John Brady
more than filled the bill. He was accepted, educated and became a
missionary to Alaska. So suitable a man was he for commissioner of
that unexplored land of wealth, that President Harrison appointed
him governor.
Who can value the worth of a boy? Like Moses, Luther, or Lincoln,
he might rise to bless a nation. Boyhood is the blossom that ripens
into manhood. It is the formative period of one’s character. Said Lord
Collingwood to a young friend, “You must establish a character
before you are twenty-five that will serve you all life.” The building of
such is the greatest earthly task, and he is the greatest man “who
chooses right with the most invincible resolution, who resists the
sorest temptation from within and without, who is most fearless
under menaces and frowns, whose reliance on truth, on virtue, and
on God, is most unfaltering.”
To aid in the growth of such is this work written. It is hoped that it
will be transformed into an epitome, a registry of the reader’s own
life—a compilation and condensation of the best things he shall
finally leave to those who survive him. For it should
—“to one of these four ends conduce,
For wisdom, piety, delight or use.”

Incorporated herein are the best things of many books; the


thoughts of noble men which by the power of a just appreciation and
of a retentive memory may be made one’s own. Of those who have
written introductions to this work, some have since retired from
their official positions, and some are dead. The stories gathered from
many sources illustrate great principles, which, if carefully heeded
will conduce to a happy and manly life; for
—“He most lives
Who thinks most, feels the noblest, acts the best.”
Success Maxims

1. Have a definite aim.


2. Go straight for it.
3. Master all details.
4. Always know more than you are expected to know.
5. Remember that difficulties are only made to be overcome.
6. Treat failures as stepping stones to further effort.
7. Never put your hand out farther than you can draw it back.
8. At times be bold; always be prudent.
9. The minority often beats the majority in the end.
10. Make good use of other men’s brains.
11. Listen well, answer cautiously, decide promptly.
12. Preserve, by all means in your power, “a sound mind in a
sound body.”
PART I
Relation to Self
CHAPTER I
Be Neat

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.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like