HTML and CSS Reference
In-Depth Information
if (this.innerHTML == “Expand All”) {
for (i = 0; i < answers.length; i++) {
answers[i].style.display = 'block';
}
this.innerHTML = “Collapse All”;
15
}
else {
for (i = 0; i < answers.length; i++) {
answers[i].style.display = 'none';
}
this.innerHTML = “Expand All”;
}
return false;
};
faq = document.getElementById(“faq”);
faq.insertBefore(expandAllDiv, faq.firstChild);
}
First, I declare the variables I use in the function, and then I start creating the elements.
The
createElement()
method of the
document
object is used to create an element. It
accepts the element name as the argument. I create the
<div>
element and then call the
setAttribute()
method to add the
id
attribute to that element. The
setAttribute()
method takes two arguments, the attribute name and the value for that attribute. Then I
create the link by creating a new
<a>
element. I set the
href
attribute to
#
, because the
event handler for the link's
onclick
event will return false anyway, and I add an
id
for
the link, too. To add the link text, I call the
document.createTextNode()
method:
expandAllLink.appendChild(document.createTextNode(“Expand All”));
I pass the results of that method call to the
appendChild()
method of
expandAllLink
,
which results in the text node being placed inside the
<a>
tag. Then on the next line I
append the link to the
<div>
, again using
appendChild()
. The last thing to do before
appending the
<div>
to an element that's already on the page (causing it to appear) is to
add the
onclick
handler to the link.
I'm again attaching the
onclick
handler using an anonymous function, as I did in the
previous example. In this case, I use the same technique I used in the previous example,
obtaining a reference to the
<div>
with the ID
faq
and then retrieving a list of
<dd>
ele-
ments inside it.
At that point, I inspect the contents of
this.innerHTML
. In an event handler,
this
is a
reference to the element upon which the event was called, so in this case, it's the link.
The
innerHTML
property contains whatever is inside that element, in this case, the link
text. If the link text is “Expand All,” I iterate over each of the answers and set their
