HTML and CSS Reference
In-Depth Information
Method
Description
Retrieves the element with the specified ID. IDs are
assigned using the
id
attribute. This is one of the
areas where JavaScript intersects with CSS.
getElementById(id)
Retrieves elements with the specified value as their
name
attribute. Usually used with forms or form fields,
both of which use the
name
attribute.
15
getElementByName(name)
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 children
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.
There are two ways to hide elements with CSS, you can set the
display
property to
none
or the
visibility
property to
hidden
. Using the
display
property will hide the element
completely, the
visibility
property hides the content in the element but leaves the
space it takes up empty. So for this case, using the
display
property makes more sense.
Every element in the document has a
style
property, and that property has its own prop-
erties for each CSS property. Here's the code that hides each of the
dd
elements:
for (i = 0; i < answers.length; i++) {
answers[i].style.display = 'none';
}
The
for
loop iterates over each of the elements, and inside the loop, I set the
display
property to
none
. When the page loads, the answers will be hidden.

