Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

542 LESSON 19: Using JavaScript in Your Pages


On the next line, I declare all the variables I use in this function. JavaScript is a bit
different from many other languages in that variables cannot have “block” scope. For
example, in most languages, if you declare a variable inside the body of an if statement,
that variable will go away once the if statement is finished. Not so in JavaScript. A vari-
able declared anywhere inside a function will be accessible from that point onward in the
function, regardless of where it was declared. For that reason, declaring all your variables
at the top of the function is one way to avoid confusing bugs.
Looking Up Elements in the Document The preceding lesson discussed the
document object a little bit and mentioned that it provides access to the full contents of
the web page. The representation of the page that is accessible via JavaScript is referred
to as the Document Object Model, or DOM. The entire page is represented as a tree,
starting at the root element, represented by the <html> tag. If you leave out the <html>
tag, the browser will add it to the DOM when it renders the page. The DOM f or this page
is shown in Figure 19.8.

FIGURE 19.8
The DOM for the
FAQ page, shown
in the Chrome
Developer Tools.

When you declare an anonymous function in an assignment state-
ment, you must make sure to include the semicolon after the
closing brace. Normally when you declare functions, a semicolon
is not needed, but because the function declaration is part of the
assignment statement, that statement has to be terminated with
a semicolon or you’ll get a syntax error when the browser tries to
interpret the JavaScript.

NOTE


Free download pdf