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

(singke) #1
ptg16476052

Hiding and Showing Content 543

19


There are a number of ways to dig into the DOM. The browser provides access to the
parent of each element, as well as its siblings and children, so you can reach any element
that way. However, navigating your way to elements in the page that way is tedious.
Fortunately, there are some shortcuts available.


These shortcuts, methods that can be called on the document object, are listed in Table
19.1.


TABLE 19.1 Methods for Accessing the DOM


Method Description


getElementsByTagName(name) Retrieves a list of elements with the supplied tag name.
This can also be called on a specific element, and it will
return a list of the descendants of that element with the
specified tag name.


getElementById(id) Retrieves the element with the specified ID. IDs are
assigned using the id attribute. This is one of the areas
in which JavaScript intersects with CSS.


getElementByName(name) Retrieves elements with the specified value as their name
attribute. Usually used with forms or form fields, both of
which use the name attribute.


To set up the expanding and collapsing properly, I must hide the answers to the questions
and bind an event to the questions that expands them when users click them. First, I need
to look up the elements I want to modify in the DOM.


faqList = document.getElementById("faq");
answers = faqList.getElementsByTagName("dd");


The first line gets the element with the ID faq. That’s the ID I assigned to my definition
list in the markup. Then the next line returns a list of all the dd elements that are chil-
dren of the element now assigned to faqList. I could skip the step of looking up the faq
list first, but then if this page included multiple definition lists, the behavior would be
applied to all of them rather than just the faq. This is also a useful precaution in case this
JavaScript file is included on more than one page. In the end, I have a list of dd elements.


Changing Styles I grabbed the list of dd elements so that they can be hidden when
the page loads. I could have hidden them using a style sheet or the style attribute of each
of the dd elements, but that wouldn’t be unobtrusive. If a user without JavaScript visited
the page, the answers to the questions would be hidden and there wouldn’t be any way to
reveal the answers. It’s better to hide them with JavaScript.



Free download pdf